Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: isAssignableFrom and reflection type checks

In Kotlin (1.0.6), through reflection I need to iterate over the members of a class (let's call it Foo), and do something based on the return type. I can write the following, which works:

Foo::class.members{ m ->
    if(Integer.TYPE.isAssignableFrom(m.returnType.javaType as Class<*>)){
        //do something here
    } else if ...
}

the problem is that the if statement (to handle kotlin.Int) is quite ugly. Is there any better way in Kotlin to achieve the same result without having to rely directly on the Java API?

like image 790
arcuri82 Avatar asked Mar 12 '26 19:03

arcuri82


1 Answers

No, there is not a better way pre-1.1 Kotlin.

You can use Int::class.javaObjectType instead of Integer.TYPE to avoid using java.lang.Integer in Kotlin code but that makes the statement even longer (although more idiomatic).

In Kotlin 1.1 you can use isSubtypeOf or query jvmErasure.allSupertypes directly.

like image 134
mfulton26 Avatar answered Mar 14 '26 09:03

mfulton26