August 2017
Intermediate to advanced
440 pages
10h
English
There are some cases where accessing the type parameter at runtime would be useful, but they are not allowed because of type erasure:
fun <T> typeCheck(s: Any) { if(s is T){ // Error: cannot check for instance of erased type: T println("The same types") } else { println("Different types") } }
To overcome JVM limitation, Kotlin allows us to use a special modifier that can preserve a type argument at runtime. We need to mark the type parameter with the reified modifier:
interface View class ProfileView: View class HomeView: View inline fun <reified T> typeCheck(s: Any) { // 1 if(s is T){ println("The same types") } else { println("Different types") } } // Usage typeCheck<ProfileView>(ProfileView()) // Prints: The ...Read now
Unlock full access