Kotlin Contracts: assert instance on reified type parameter











up vote
3
down vote

favorite
1












I'm trying to write an assert function that checks if a given object is of a type T:



@UseExperimental(ExperimentalContracts::class)
inline fun <reified T> assertIsInstance(value: Any?) {
contract {
returns() implies (value is T)
}

Assertions.assertThat(value).isInstanceOf(T::class.java)
}


The function uses AssertJ to do the concrete assertion but I'm willing to let the compiler know that after its execution, the value is of type T so that a smartcast is possible. It seems like this does not work because:



Error in contract description: references to type parameters are forbidden in contracts



Is there another way to achieve this behavior? What's the issue here? Will this eventually be possible?



(Using Kotlin v1.3)










share|improve this question




























    up vote
    3
    down vote

    favorite
    1












    I'm trying to write an assert function that checks if a given object is of a type T:



    @UseExperimental(ExperimentalContracts::class)
    inline fun <reified T> assertIsInstance(value: Any?) {
    contract {
    returns() implies (value is T)
    }

    Assertions.assertThat(value).isInstanceOf(T::class.java)
    }


    The function uses AssertJ to do the concrete assertion but I'm willing to let the compiler know that after its execution, the value is of type T so that a smartcast is possible. It seems like this does not work because:



    Error in contract description: references to type parameters are forbidden in contracts



    Is there another way to achieve this behavior? What's the issue here? Will this eventually be possible?



    (Using Kotlin v1.3)










    share|improve this question


























      up vote
      3
      down vote

      favorite
      1









      up vote
      3
      down vote

      favorite
      1






      1





      I'm trying to write an assert function that checks if a given object is of a type T:



      @UseExperimental(ExperimentalContracts::class)
      inline fun <reified T> assertIsInstance(value: Any?) {
      contract {
      returns() implies (value is T)
      }

      Assertions.assertThat(value).isInstanceOf(T::class.java)
      }


      The function uses AssertJ to do the concrete assertion but I'm willing to let the compiler know that after its execution, the value is of type T so that a smartcast is possible. It seems like this does not work because:



      Error in contract description: references to type parameters are forbidden in contracts



      Is there another way to achieve this behavior? What's the issue here? Will this eventually be possible?



      (Using Kotlin v1.3)










      share|improve this question















      I'm trying to write an assert function that checks if a given object is of a type T:



      @UseExperimental(ExperimentalContracts::class)
      inline fun <reified T> assertIsInstance(value: Any?) {
      contract {
      returns() implies (value is T)
      }

      Assertions.assertThat(value).isInstanceOf(T::class.java)
      }


      The function uses AssertJ to do the concrete assertion but I'm willing to let the compiler know that after its execution, the value is of type T so that a smartcast is possible. It seems like this does not work because:



      Error in contract description: references to type parameters are forbidden in contracts



      Is there another way to achieve this behavior? What's the issue here? Will this eventually be possible?



      (Using Kotlin v1.3)







      generics kotlin contract assertj kotlin-reified-type-parameters






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 8 at 10:34

























      asked Nov 8 at 10:29









      s1m0nw1

      23.5k53696




      23.5k53696
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote













          At some point there were some (deeply technical) concerns regarding support of such constructions in an IDE, but it's possible that this limitation will be relaxed in the future.






          share|improve this answer





















          • thanks for the response. Any alternative approach to implement such a contract?
            – s1m0nw1
            Nov 8 at 12:18


















          up vote
          1
          down vote













          This has been bugging me for a couple hours, especially since this is possible:



          val x: Any = "string"
          require(x is String)
          val len = x.length


          The compiler is clearly able to understand these, so this is likely a limitation of the contracts themselves.



          I've spent a while now trying to come up with some workarounds. For reference:



          @UseExperimental(ExperimentalContracts::class)
          inline fun <reified T> assertIsInstance(value: Any?) {
          contract {
          returns() implies T::class.isInstance(value))
          }
          if(value !is T){
          throw java.lang.IllegalArgumentException("Incorrect type");
          }
          }


          "Unsupported construct"



          @UseExperimental(ExperimentalContracts::class)
          inline fun <reified T> assertIsInstance(value: Any?, condition: Boolean = value is T) {
          contract {
          returns() implies condition
          }
          if(!condition)
          throw IllegalArgumentException("Incorrect type");
          }


          Compiles, but doesn't enable smart cast. The original motivation behind that one was placing a boolean in front of the contract, but contracts need to be the first part of a function, which made that impossible. You might as well remove the contract; it's useless in this case.



          This was my last try:



          @UseExperimental(ExperimentalContracts::class)
          inline fun assertIsInstance(value: Any?, cls: KClass<out Any>) {
          contract {
          returns() implies (cls.isInstance(value))
          }
          if(!cls.isInstance(value))
          throw IllegalArgumentException("");
          }


          Another "unsupported construct".



          Somehow I ended up with this:



          @UseExperimental(ExperimentalContracts::class)
          inline fun assertIsInstance(value: Any?) {
          contract {
          returns() implies (value.hashCode() == 0)
          }
          if(value.hashCode() != 0)
          throw java.lang.IllegalArgumentException();
          }


          But this gives a new error: only references to parameters are allowed in contract description.



          TL;DR:



          It doesn't look like you can. Sneaking it in like I did in the second example doesn't trigger smart cast, and the rest don't work due to various compiler errors.



          At least for now, there doesn't appear to be a way. You could of course open an issue in the Kotlin repo and ask for something like this, but for now, it doesn't appear to be possible.






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205855%2fkotlin-contracts-assert-instance-on-reified-type-parameter%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            2
            down vote













            At some point there were some (deeply technical) concerns regarding support of such constructions in an IDE, but it's possible that this limitation will be relaxed in the future.






            share|improve this answer





















            • thanks for the response. Any alternative approach to implement such a contract?
              – s1m0nw1
              Nov 8 at 12:18















            up vote
            2
            down vote













            At some point there were some (deeply technical) concerns regarding support of such constructions in an IDE, but it's possible that this limitation will be relaxed in the future.






            share|improve this answer





















            • thanks for the response. Any alternative approach to implement such a contract?
              – s1m0nw1
              Nov 8 at 12:18













            up vote
            2
            down vote










            up vote
            2
            down vote









            At some point there were some (deeply technical) concerns regarding support of such constructions in an IDE, but it's possible that this limitation will be relaxed in the future.






            share|improve this answer












            At some point there were some (deeply technical) concerns regarding support of such constructions in an IDE, but it's possible that this limitation will be relaxed in the future.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 8 at 11:40









            Dmitry Savvinov

            212




            212












            • thanks for the response. Any alternative approach to implement such a contract?
              – s1m0nw1
              Nov 8 at 12:18


















            • thanks for the response. Any alternative approach to implement such a contract?
              – s1m0nw1
              Nov 8 at 12:18
















            thanks for the response. Any alternative approach to implement such a contract?
            – s1m0nw1
            Nov 8 at 12:18




            thanks for the response. Any alternative approach to implement such a contract?
            – s1m0nw1
            Nov 8 at 12:18












            up vote
            1
            down vote













            This has been bugging me for a couple hours, especially since this is possible:



            val x: Any = "string"
            require(x is String)
            val len = x.length


            The compiler is clearly able to understand these, so this is likely a limitation of the contracts themselves.



            I've spent a while now trying to come up with some workarounds. For reference:



            @UseExperimental(ExperimentalContracts::class)
            inline fun <reified T> assertIsInstance(value: Any?) {
            contract {
            returns() implies T::class.isInstance(value))
            }
            if(value !is T){
            throw java.lang.IllegalArgumentException("Incorrect type");
            }
            }


            "Unsupported construct"



            @UseExperimental(ExperimentalContracts::class)
            inline fun <reified T> assertIsInstance(value: Any?, condition: Boolean = value is T) {
            contract {
            returns() implies condition
            }
            if(!condition)
            throw IllegalArgumentException("Incorrect type");
            }


            Compiles, but doesn't enable smart cast. The original motivation behind that one was placing a boolean in front of the contract, but contracts need to be the first part of a function, which made that impossible. You might as well remove the contract; it's useless in this case.



            This was my last try:



            @UseExperimental(ExperimentalContracts::class)
            inline fun assertIsInstance(value: Any?, cls: KClass<out Any>) {
            contract {
            returns() implies (cls.isInstance(value))
            }
            if(!cls.isInstance(value))
            throw IllegalArgumentException("");
            }


            Another "unsupported construct".



            Somehow I ended up with this:



            @UseExperimental(ExperimentalContracts::class)
            inline fun assertIsInstance(value: Any?) {
            contract {
            returns() implies (value.hashCode() == 0)
            }
            if(value.hashCode() != 0)
            throw java.lang.IllegalArgumentException();
            }


            But this gives a new error: only references to parameters are allowed in contract description.



            TL;DR:



            It doesn't look like you can. Sneaking it in like I did in the second example doesn't trigger smart cast, and the rest don't work due to various compiler errors.



            At least for now, there doesn't appear to be a way. You could of course open an issue in the Kotlin repo and ask for something like this, but for now, it doesn't appear to be possible.






            share|improve this answer

























              up vote
              1
              down vote













              This has been bugging me for a couple hours, especially since this is possible:



              val x: Any = "string"
              require(x is String)
              val len = x.length


              The compiler is clearly able to understand these, so this is likely a limitation of the contracts themselves.



              I've spent a while now trying to come up with some workarounds. For reference:



              @UseExperimental(ExperimentalContracts::class)
              inline fun <reified T> assertIsInstance(value: Any?) {
              contract {
              returns() implies T::class.isInstance(value))
              }
              if(value !is T){
              throw java.lang.IllegalArgumentException("Incorrect type");
              }
              }


              "Unsupported construct"



              @UseExperimental(ExperimentalContracts::class)
              inline fun <reified T> assertIsInstance(value: Any?, condition: Boolean = value is T) {
              contract {
              returns() implies condition
              }
              if(!condition)
              throw IllegalArgumentException("Incorrect type");
              }


              Compiles, but doesn't enable smart cast. The original motivation behind that one was placing a boolean in front of the contract, but contracts need to be the first part of a function, which made that impossible. You might as well remove the contract; it's useless in this case.



              This was my last try:



              @UseExperimental(ExperimentalContracts::class)
              inline fun assertIsInstance(value: Any?, cls: KClass<out Any>) {
              contract {
              returns() implies (cls.isInstance(value))
              }
              if(!cls.isInstance(value))
              throw IllegalArgumentException("");
              }


              Another "unsupported construct".



              Somehow I ended up with this:



              @UseExperimental(ExperimentalContracts::class)
              inline fun assertIsInstance(value: Any?) {
              contract {
              returns() implies (value.hashCode() == 0)
              }
              if(value.hashCode() != 0)
              throw java.lang.IllegalArgumentException();
              }


              But this gives a new error: only references to parameters are allowed in contract description.



              TL;DR:



              It doesn't look like you can. Sneaking it in like I did in the second example doesn't trigger smart cast, and the rest don't work due to various compiler errors.



              At least for now, there doesn't appear to be a way. You could of course open an issue in the Kotlin repo and ask for something like this, but for now, it doesn't appear to be possible.






              share|improve this answer























                up vote
                1
                down vote










                up vote
                1
                down vote









                This has been bugging me for a couple hours, especially since this is possible:



                val x: Any = "string"
                require(x is String)
                val len = x.length


                The compiler is clearly able to understand these, so this is likely a limitation of the contracts themselves.



                I've spent a while now trying to come up with some workarounds. For reference:



                @UseExperimental(ExperimentalContracts::class)
                inline fun <reified T> assertIsInstance(value: Any?) {
                contract {
                returns() implies T::class.isInstance(value))
                }
                if(value !is T){
                throw java.lang.IllegalArgumentException("Incorrect type");
                }
                }


                "Unsupported construct"



                @UseExperimental(ExperimentalContracts::class)
                inline fun <reified T> assertIsInstance(value: Any?, condition: Boolean = value is T) {
                contract {
                returns() implies condition
                }
                if(!condition)
                throw IllegalArgumentException("Incorrect type");
                }


                Compiles, but doesn't enable smart cast. The original motivation behind that one was placing a boolean in front of the contract, but contracts need to be the first part of a function, which made that impossible. You might as well remove the contract; it's useless in this case.



                This was my last try:



                @UseExperimental(ExperimentalContracts::class)
                inline fun assertIsInstance(value: Any?, cls: KClass<out Any>) {
                contract {
                returns() implies (cls.isInstance(value))
                }
                if(!cls.isInstance(value))
                throw IllegalArgumentException("");
                }


                Another "unsupported construct".



                Somehow I ended up with this:



                @UseExperimental(ExperimentalContracts::class)
                inline fun assertIsInstance(value: Any?) {
                contract {
                returns() implies (value.hashCode() == 0)
                }
                if(value.hashCode() != 0)
                throw java.lang.IllegalArgumentException();
                }


                But this gives a new error: only references to parameters are allowed in contract description.



                TL;DR:



                It doesn't look like you can. Sneaking it in like I did in the second example doesn't trigger smart cast, and the rest don't work due to various compiler errors.



                At least for now, there doesn't appear to be a way. You could of course open an issue in the Kotlin repo and ask for something like this, but for now, it doesn't appear to be possible.






                share|improve this answer












                This has been bugging me for a couple hours, especially since this is possible:



                val x: Any = "string"
                require(x is String)
                val len = x.length


                The compiler is clearly able to understand these, so this is likely a limitation of the contracts themselves.



                I've spent a while now trying to come up with some workarounds. For reference:



                @UseExperimental(ExperimentalContracts::class)
                inline fun <reified T> assertIsInstance(value: Any?) {
                contract {
                returns() implies T::class.isInstance(value))
                }
                if(value !is T){
                throw java.lang.IllegalArgumentException("Incorrect type");
                }
                }


                "Unsupported construct"



                @UseExperimental(ExperimentalContracts::class)
                inline fun <reified T> assertIsInstance(value: Any?, condition: Boolean = value is T) {
                contract {
                returns() implies condition
                }
                if(!condition)
                throw IllegalArgumentException("Incorrect type");
                }


                Compiles, but doesn't enable smart cast. The original motivation behind that one was placing a boolean in front of the contract, but contracts need to be the first part of a function, which made that impossible. You might as well remove the contract; it's useless in this case.



                This was my last try:



                @UseExperimental(ExperimentalContracts::class)
                inline fun assertIsInstance(value: Any?, cls: KClass<out Any>) {
                contract {
                returns() implies (cls.isInstance(value))
                }
                if(!cls.isInstance(value))
                throw IllegalArgumentException("");
                }


                Another "unsupported construct".



                Somehow I ended up with this:



                @UseExperimental(ExperimentalContracts::class)
                inline fun assertIsInstance(value: Any?) {
                contract {
                returns() implies (value.hashCode() == 0)
                }
                if(value.hashCode() != 0)
                throw java.lang.IllegalArgumentException();
                }


                But this gives a new error: only references to parameters are allowed in contract description.



                TL;DR:



                It doesn't look like you can. Sneaking it in like I did in the second example doesn't trigger smart cast, and the rest don't work due to various compiler errors.



                At least for now, there doesn't appear to be a way. You could of course open an issue in the Kotlin repo and ask for something like this, but for now, it doesn't appear to be possible.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 8 at 15:23









                Zoe

                10.2k73475




                10.2k73475






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205855%2fkotlin-contracts-assert-instance-on-reified-type-parameter%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Schultheiß

                    Verwaltungsgliederung Dänemarks

                    Liste der Kulturdenkmale in Wilsdruff