jeudi 15 décembre 2016

How to compare a Class<*> against a Java boxed primitive type without kotlin compiler warnings

I'm using Kotlin to write something that works with Java's reflection APIs. My input is a Class<*> and I need to decide whether that type is a double or integer, but I need to support both primitives and the boxed nullable types that Java uses.

This toy example does what I'm trying to do:

when(type) {
    java.lang.Double::class.java, Double::class.java -> TypesEnum.DOUBLE
    java.lang.Integer::class.java, Int::class.java   -> TypesEnum.INT
    else -> throw IllegalArgumentException("type")
}

But, this approach generates the following warnings from the Kotlin compiler:

Warning:(22, 13) Kotlin: This class shouldn't be used in Kotlin. Use kotlin.Double instead. Warning:(23, 13) Kotlin: This class shouldn't be used in Kotlin. Use kotlin.Int instead.

However, Int?::class.java is a syntax error, the approaches suggested on an earlier question require a KClass instead of a Class<*> (and the .kotlin extension method crashes on some of my inputs). What's the correct Kotlin way to perform this kind of check?





Aucun commentaire:

Enregistrer un commentaire