https://kotlinlang.org logo
Title
r

Rohan Maity

06/30/2022, 7:03 AM
Is there any way to store reified types to a variable?
y

Youssef Shoaib [MOD]

06/30/2022, 7:06 AM
Not directly, but you can store their class:
var myGlobalVariable: KClass<*>? = null 
// In your reified function 
myGlobalVariable = T::class
I believe there's also
typeOf<T>()
which gives you a
KType
instead but I can't remember if that's the right syntax for it or not
r

Rohan Maity

06/30/2022, 8:16 AM
Actually I wanted to use these variables like this in android fragment dsl
fragment<MyVariable>()
Actual usage
fragment<HomeFragment>
But this variable thing does not work here
r

ribesg

06/30/2022, 9:18 AM
Nah generics are not a thing at runtime
y

Youssef Shoaib [MOD]

06/30/2022, 9:30 AM
Well, with a KClass instance you can access its constructors and therefore invoke its no-args constructor.
@ribesg Reified generics are absolutely real at runtime though. It's because the function is inline so the compiler replaces the function with its body and with the Reified type substituted in.
r

Rohan Maity

06/30/2022, 9:39 AM
Ok I have to create object in the end?
So does the reified type as mentioned in the above example work by creating objects?
r

ribesg

06/30/2022, 9:41 AM
No. What you want to do is not possible.
@Youssef Shoaib [MOD] you just explained how generics aren’t there anymore at runtime in the case of reified type
To clarify, Rohan wants to do this in a reified function:
val U = _somethingWithT_
someGenericFunction<U>()
And that is entirely impossible as the first instance of ‘U’ here represents a variable, something that exists at runtime, while the second instance of ‘U’ represents something that doesn’t exists at runtime. It’s like two different universes that don’t meet, nothing can be in both
r

Rohan Maity

06/30/2022, 4:39 PM
ok understood why it is not possible