Checking type in generic

Apologies for what is most likely a very simple question, but although I can see how to the in this example where a parameter of type T

fun test(arg:T){
when(arg){
is Int → { …

but what I cannot see is how to test T directly, for cases where no type parameter exists.

fun <T> test() : T {
    when(T){      // this won't work perhaps T::something? 
        is Int -> { ........ 

is obviously wrong as a property cannot be substituted with a type… but how can you work with T?

2 Likes

First of all: JVM removes most of generic information and so does Kotlin. So fun <T> test() : T at runtime becomes fun test() : Object and any information about T is lost. And you want to make your check at runtime, so you out of luck. At least with similar Java code.

But Kotlin has something called reified generics. You can mark type parameter T of the inline function as reified you’ll be able to check it at runtime. With this feature you can write your check as follows:

inline fun <reified T> test() : T {
  when (T::class) {
    Int::class -> println("Int")
    else -> println("${T::class}")

Also note, that at runtime you will receive java.lang.Integer, not kotlin.Int.

5 Likes

Thanks. That is well explained. Works well for normal classes. Actually needs “java.lang.Integer::class ->” to work for an though, as you suggested.

Can you write example of using for generic class. I want to know T:class.java

class SomeClass <T: SomeClass>{

inline fun getGenericTClass() = R::class.java
}