mercredi 24 février 2016

Kotlin: Generics, reflection and the difference between type T and T:Any

If I try to access the javaClass of a generic type T the Kotlin compiler complains that T is not a subtype of kotlin.Any

class Foo<T> (val t: T ){
    val cls = t.javaClass // Error, T is not a subtype of kotlin.Any
}

If define T as a subtype of Any everything works ok.

class Bar<T:Any> (val t: T ){
    val cls = t.javaClass // OK
}

Q1) If type ´T´ is not a subtype of ´Any´ which class/classes can it be a subtype of ?

Q2) Do a javaClass exist for all instances of T and if so how do I access it ?





Aucun commentaire:

Enregistrer un commentaire