Calling a fun with reified type parameter if you just have a KClass object?How does the reified keyword in Kotlin work?Why shouldn't Java enum literals be able to have generic type parameters?How do I access a Java static method on a Kotlin subclass?How can I store reified type data in instance fields in Kotlin?Kotlin reified type parameter as function parameterKotlin - Cannot use 'T' as reified type parameter. Use a class insteadHow type erasure worksWrong inference for reified type parameter in KotlinHow do you write secondary constructors for a class with type parameters?Using Fuel's responseObject with a generic call siteGet runtime class of a generic type parameter in Kotlin without reified keyword

How should I avoid someone patenting technology in my paper/poster?

Can さくじつ and きのう be used the same way?

Can one guy with a duplicator initiate a nuclear apocalypse?

What do solvers like Gurobi and CPLEX do when they run into hard instances of MIP

Very lazy puppy

What did the controller say during my approach to land (audio clip)?

Persuading players to be less attached to a pre-session 0 character concept

Should I inform my future product owner that there is a good chance that a team member will leave the company soon?

Why can't we use uninitialized local variable to access static content of its type?

Inquiry answerer

Audire, with accusative or dative?

Debussy as term for bathroom?

Do household ovens ventilate heat to the outdoors?

Why do things cool down?

Flying pigs arrive

I feel like most of my characters are the same, what can I do?

Who are the people reviewing far more papers than they're submitting for review?

Is it possible that the shadow of The Moon is a single dot during solar eclipse?

Get the encrypted payload from an unencrypted wrapper PDF document

How do you determine which representation of a function to use for Newton's method?

Madrid to London w/ Expired 90/180 days stay as US citizen

What's the purpose of autocorrelation?

Quick Kurodoko Puzzle: Threes and Triples

All numbers in a 5x5 Minesweeper grid



Calling a fun with reified type parameter if you just have a KClass object?


How does the reified keyword in Kotlin work?Why shouldn't Java enum literals be able to have generic type parameters?How do I access a Java static method on a Kotlin subclass?How can I store reified type data in instance fields in Kotlin?Kotlin reified type parameter as function parameterKotlin - Cannot use 'T' as reified type parameter. Use a class insteadHow type erasure worksWrong inference for reified type parameter in KotlinHow do you write secondary constructors for a class with type parameters?Using Fuel's responseObject with a generic call siteGet runtime class of a generic type parameter in Kotlin without reified keyword






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















One can only use reified type parameters with inline functions. So if I want such a parameter for a class I need a trick like this:



class Foo<T : Any>(private val clazz: KClass<T>) 
companion object
inline fun <reified T: Any> create() = Foo(T::class)




I can then create instances of Foo like this:



val foo = Foo.create<Bar>()


Within Foo I have access clazz but my question is can I then use clazz when I need to call methods that require a reified type parameter`?



E.g. within Foo I'd like to add a method like this:



fun print(list: List<Alpha>) 
list.filterIsInstance<T>().forEach print(it)



But as far as I can see there's no way to get from clazz to something I can use as a type parameter here.



And yes, I know there's a form of filterIsInstance that takes a Class so I can do:



list.filterIsInstance(clazz.java).forEach print(it) 


However many libraries contain methods where both forms (explicit class parameter and reified type parameter) are not provided.



E.g. the Jackson Kotlin Extensions.kt. Actually this isn't a great example as the non-reified equivalents are all one-liners but this isn't always the case - then you end up unpacking the implementation of the reified-type-parameter method into your code.










share|improve this question
























  • Given the description of how reification works in this other SO answer it seems clear anything to do with reified is resolved at compile time so you cannot hope to do anything with a KClass or Class object that you've acquired at runtime (all methods involving reified have been inlined at this point and essentially don't exist in any real sense at runtime).

    – George Hawkins
    Apr 5 at 14:40

















4















One can only use reified type parameters with inline functions. So if I want such a parameter for a class I need a trick like this:



class Foo<T : Any>(private val clazz: KClass<T>) 
companion object
inline fun <reified T: Any> create() = Foo(T::class)




I can then create instances of Foo like this:



val foo = Foo.create<Bar>()


Within Foo I have access clazz but my question is can I then use clazz when I need to call methods that require a reified type parameter`?



E.g. within Foo I'd like to add a method like this:



fun print(list: List<Alpha>) 
list.filterIsInstance<T>().forEach print(it)



But as far as I can see there's no way to get from clazz to something I can use as a type parameter here.



And yes, I know there's a form of filterIsInstance that takes a Class so I can do:



list.filterIsInstance(clazz.java).forEach print(it) 


However many libraries contain methods where both forms (explicit class parameter and reified type parameter) are not provided.



E.g. the Jackson Kotlin Extensions.kt. Actually this isn't a great example as the non-reified equivalents are all one-liners but this isn't always the case - then you end up unpacking the implementation of the reified-type-parameter method into your code.










share|improve this question
























  • Given the description of how reification works in this other SO answer it seems clear anything to do with reified is resolved at compile time so you cannot hope to do anything with a KClass or Class object that you've acquired at runtime (all methods involving reified have been inlined at this point and essentially don't exist in any real sense at runtime).

    – George Hawkins
    Apr 5 at 14:40













4












4








4








One can only use reified type parameters with inline functions. So if I want such a parameter for a class I need a trick like this:



class Foo<T : Any>(private val clazz: KClass<T>) 
companion object
inline fun <reified T: Any> create() = Foo(T::class)




I can then create instances of Foo like this:



val foo = Foo.create<Bar>()


Within Foo I have access clazz but my question is can I then use clazz when I need to call methods that require a reified type parameter`?



E.g. within Foo I'd like to add a method like this:



fun print(list: List<Alpha>) 
list.filterIsInstance<T>().forEach print(it)



But as far as I can see there's no way to get from clazz to something I can use as a type parameter here.



And yes, I know there's a form of filterIsInstance that takes a Class so I can do:



list.filterIsInstance(clazz.java).forEach print(it) 


However many libraries contain methods where both forms (explicit class parameter and reified type parameter) are not provided.



E.g. the Jackson Kotlin Extensions.kt. Actually this isn't a great example as the non-reified equivalents are all one-liners but this isn't always the case - then you end up unpacking the implementation of the reified-type-parameter method into your code.










share|improve this question














One can only use reified type parameters with inline functions. So if I want such a parameter for a class I need a trick like this:



class Foo<T : Any>(private val clazz: KClass<T>) 
companion object
inline fun <reified T: Any> create() = Foo(T::class)




I can then create instances of Foo like this:



val foo = Foo.create<Bar>()


Within Foo I have access clazz but my question is can I then use clazz when I need to call methods that require a reified type parameter`?



E.g. within Foo I'd like to add a method like this:



fun print(list: List<Alpha>) 
list.filterIsInstance<T>().forEach print(it)



But as far as I can see there's no way to get from clazz to something I can use as a type parameter here.



And yes, I know there's a form of filterIsInstance that takes a Class so I can do:



list.filterIsInstance(clazz.java).forEach print(it) 


However many libraries contain methods where both forms (explicit class parameter and reified type parameter) are not provided.



E.g. the Jackson Kotlin Extensions.kt. Actually this isn't a great example as the non-reified equivalents are all one-liners but this isn't always the case - then you end up unpacking the implementation of the reified-type-parameter method into your code.







generics kotlin kotlin-reified-type-parameters






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 14:12









George HawkinsGeorge Hawkins

24.7k5 gold badges19 silver badges33 bronze badges




24.7k5 gold badges19 silver badges33 bronze badges















  • Given the description of how reification works in this other SO answer it seems clear anything to do with reified is resolved at compile time so you cannot hope to do anything with a KClass or Class object that you've acquired at runtime (all methods involving reified have been inlined at this point and essentially don't exist in any real sense at runtime).

    – George Hawkins
    Apr 5 at 14:40

















  • Given the description of how reification works in this other SO answer it seems clear anything to do with reified is resolved at compile time so you cannot hope to do anything with a KClass or Class object that you've acquired at runtime (all methods involving reified have been inlined at this point and essentially don't exist in any real sense at runtime).

    – George Hawkins
    Apr 5 at 14:40
















Given the description of how reification works in this other SO answer it seems clear anything to do with reified is resolved at compile time so you cannot hope to do anything with a KClass or Class object that you've acquired at runtime (all methods involving reified have been inlined at this point and essentially don't exist in any real sense at runtime).

– George Hawkins
Apr 5 at 14:40





Given the description of how reification works in this other SO answer it seems clear anything to do with reified is resolved at compile time so you cannot hope to do anything with a KClass or Class object that you've acquired at runtime (all methods involving reified have been inlined at this point and essentially don't exist in any real sense at runtime).

– George Hawkins
Apr 5 at 14:40












2 Answers
2






active

oldest

votes


















0
















no, because those functions are inline, they are inlined at compiletime
and a Class or KClass is using reflection at runtime



there are some tricks that you can do.. like with the companion class, but that does nto need the KClass<T> at all.. anything else that provides a generic argument of T would work just as well for the reified type info



PS: reflection also cannot help you reliably because inline functions do not really exist at runtime, as explained by their modifier inline






share|improve this answer
































    0
















    Unless I am missing something, everything you can do with T in a function with reified T can be translated to a use of KClass: e.g. x is T becomes clazz.isInstance(x), x as T becomes clazz.cast(x), calls of other functions with reified type parameters are translated recursively, etc. Since the function has to be inline, all APIs it uses are visible at the call site so the translation can be made there.



    But there's no automatic way to do this translation, as far as I know.






    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',
      autoActivateHeartbeat: false,
      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/4.0/"u003ecc by-sa 4.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%2f55399737%2fcalling-a-fun-with-reified-type-parameter-if-you-just-have-a-kclass-object%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









      0
















      no, because those functions are inline, they are inlined at compiletime
      and a Class or KClass is using reflection at runtime



      there are some tricks that you can do.. like with the companion class, but that does nto need the KClass<T> at all.. anything else that provides a generic argument of T would work just as well for the reified type info



      PS: reflection also cannot help you reliably because inline functions do not really exist at runtime, as explained by their modifier inline






      share|improve this answer





























        0
















        no, because those functions are inline, they are inlined at compiletime
        and a Class or KClass is using reflection at runtime



        there are some tricks that you can do.. like with the companion class, but that does nto need the KClass<T> at all.. anything else that provides a generic argument of T would work just as well for the reified type info



        PS: reflection also cannot help you reliably because inline functions do not really exist at runtime, as explained by their modifier inline






        share|improve this answer



























          0














          0










          0









          no, because those functions are inline, they are inlined at compiletime
          and a Class or KClass is using reflection at runtime



          there are some tricks that you can do.. like with the companion class, but that does nto need the KClass<T> at all.. anything else that provides a generic argument of T would work just as well for the reified type info



          PS: reflection also cannot help you reliably because inline functions do not really exist at runtime, as explained by their modifier inline






          share|improve this answer













          no, because those functions are inline, they are inlined at compiletime
          and a Class or KClass is using reflection at runtime



          there are some tricks that you can do.. like with the companion class, but that does nto need the KClass<T> at all.. anything else that provides a generic argument of T would work just as well for the reified type info



          PS: reflection also cannot help you reliably because inline functions do not really exist at runtime, as explained by their modifier inline







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 28 at 15:06









          NikkyNikky

          3231 silver badge8 bronze badges




          3231 silver badge8 bronze badges


























              0
















              Unless I am missing something, everything you can do with T in a function with reified T can be translated to a use of KClass: e.g. x is T becomes clazz.isInstance(x), x as T becomes clazz.cast(x), calls of other functions with reified type parameters are translated recursively, etc. Since the function has to be inline, all APIs it uses are visible at the call site so the translation can be made there.



              But there's no automatic way to do this translation, as far as I know.






              share|improve this answer





























                0
















                Unless I am missing something, everything you can do with T in a function with reified T can be translated to a use of KClass: e.g. x is T becomes clazz.isInstance(x), x as T becomes clazz.cast(x), calls of other functions with reified type parameters are translated recursively, etc. Since the function has to be inline, all APIs it uses are visible at the call site so the translation can be made there.



                But there's no automatic way to do this translation, as far as I know.






                share|improve this answer



























                  0














                  0










                  0









                  Unless I am missing something, everything you can do with T in a function with reified T can be translated to a use of KClass: e.g. x is T becomes clazz.isInstance(x), x as T becomes clazz.cast(x), calls of other functions with reified type parameters are translated recursively, etc. Since the function has to be inline, all APIs it uses are visible at the call site so the translation can be made there.



                  But there's no automatic way to do this translation, as far as I know.






                  share|improve this answer













                  Unless I am missing something, everything you can do with T in a function with reified T can be translated to a use of KClass: e.g. x is T becomes clazz.isInstance(x), x as T becomes clazz.cast(x), calls of other functions with reified type parameters are translated recursively, etc. Since the function has to be inline, all APIs it uses are visible at the call site so the translation can be made there.



                  But there's no automatic way to do this translation, as far as I know.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 17:39









                  Alexey RomanovAlexey Romanov

                  118k28 gold badges227 silver badges370 bronze badges




                  118k28 gold badges227 silver badges370 bronze badges































                      draft saved

                      draft discarded















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55399737%2fcalling-a-fun-with-reified-type-parameter-if-you-just-have-a-kclass-object%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

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript