Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check generic type in Kotlin?

Tags:

kotlin

I have class

class Generic<T : SuperType>() 

and this code is't correct

fun typeCheck(s: SuperType): Unit {             when(s){                 is T -> //do some thin             }         } 

but cast s to type T s as T show warning - unsafe cast.
How check that s is type T?

like image 333
andreich Avatar asked Oct 15 '15 10:10

andreich


People also ask

How can I check for generic type in Kotlin?

There are no direct ways to do this in Kotlin. In order to check the generic type, we need to create an instance of the generic class<T> and then we can compare the same with our class.

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

How do I check my Kotlin data type?

You can use b::class. simpleName that will return type of object as String . You don't have to initialize type of a variable and later you want to check the type of variable.

What is in and out in Kotlin Generics?

In the event one generic class uses the generic type as input and output to it's function, then no in or out is used. It is invariant.


2 Answers

If you need to check if something is of generic type T you need to to have an instance of Class<T> to check against. This is a common technique in Java however in Kotlin we can make use of an inlined factory method that gets us the class object.

class Generic<T : Any>(val klass: Class<T>) {     companion object {         inline operator fun <reified T : Any>invoke() = Generic(T::class.java)     }      fun checkType(t: Any) {         when {             klass.isAssignableFrom(t.javaClass) -> println("Correct type")             else -> println("Wrong type")        }      } }  fun main(vararg args: String) {     Generic<String>().checkType("foo")     Generic<String>().checkType(1) } 
like image 86
Kirill Rakhman Avatar answered Oct 02 '22 09:10

Kirill Rakhman


Generic types are not reified on the JVM at runtime, so there's no way to do this in Kotlin. The warning is correct because the compiler can't possibly generate any instruction that will fail when the cast is done, so the cast is unchecked, meaning that the program may or may not break at some point later instead.

A related feature which might be of use is reified type parameters in inline functions. Classes can't have reified type parameters though, so if you elaborate a bit more on your use case, I can try helping you achieve what you seem to need.

like image 38
Alexander Udalov Avatar answered Oct 02 '22 08:10

Alexander Udalov