arcuri82
arcuri82

Reputation: 970

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?

Upvotes: 3

Views: 9391

Answers (1)

mfulton26
mfulton26

Reputation: 31234

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.

Upvotes: 2

Related Questions