Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I get the class of a generic parameter?

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)?

like image 783
danielspaniol Avatar asked Sep 12 '17 16:09

danielspaniol


People also ask

How do I get a class instance of generic type T?

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.

How do you find the class name for a generic type?

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.

How do you indicate that a class has a generic type parameter?

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.


1 Answers

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 } 
like image 199
Todd Avatar answered Sep 26 '22 15:09

Todd