How does Kotlin support reification if it is not s...
# announcements
k
How does Kotlin support reification if it is not supported by JVM
Is clazz.newInstance() expensive?
c
What happens is the function is removed at compile time and code is inlined. So if you had
Copy code
inline fun <reified T> test(): Any {
    return T::class.java
}

println(test<String>())
in the compiled code you'll see something like
Copy code
Class var1 = String.class;
System.out.println(var1);
This is why Kotlin can only reify params of
inline
functions.
as for the
newInstance
, yes it is more expensive than
new Clazz()
k
Actually i have a custom list impl which requires to create instance in a fun call but I can't do a
new T()
is there any way ither than reflection? PS it is a java+Kt proj
c
it's a bit hard for me to understand the requirements without seeing an example. Can you provide one?
m
@kartikpatodi Let your function or class know how to create the object by taking a lambda as a parameter. That will let you avoid reified generics. Something like this:
Copy code
class SomeClass<T>(
  private val createT: () -> T
) {
    fun create(): T = createT()
}
2
Then you can instantiate your class like this:
SomeClass<MyClass> { MyClass() }
k
Actually i have a use case where I have to create
n
instances inside the function but and i tried with reified but it is eventually creating
Class
object in the bytecode
m
But you can call that lambda as many times as you want.
k
But will it work with java code?
m
Yes. There's no magic involved 🙂
Instantiation in Java would be like this:
new SomeClass<MyClass>(MyClass::new);
k
Ok I'll try with that
@Czar @marstran Something like this https://pl.kotl.in/Hy7UVZKYV But better 😅
m
@kartikpatodi No, don't use the class object. No reflection is needed. Just do this instead: https://pl.kotl.in/HkEaqZYt4
k
Cool thanks @marstran
Only if java supported reified types like C#
m
I don't really get what you need the reified type for. 😉