I have a function which takes one argument of a generic type and I want to access the class of it:
fun <T> test(t: T) { t::class }
This fails with "expression in class literal has nullable type". That's ok, I understand it (I could use Any?
as my T
and null
as the value).
But if I change it to guaranty that t
is not-null it still fails with the same error message:
fun <T> test(t: T) { t!!::class }
In which case can t!!::class
still cause trouble?
Is there a way to get the class without using Any (or casting to Any)?
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
Basically if you do class Foo implements List<Integer> then you can get the generic type. Doing something like List<Integer> foo; you cannot because of type erasure. Not all generic types are erased.
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
Change your type to indicate it is not-nullable and it should work. You can do this by indicating that T
needs to extend Any
(rather than Any?
).
fun <T : Any> test(t: T) { t::class }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With