How does the reified keyword in Kotlin work?

Technology CommunityCategory: KotlinHow does the reified keyword in Kotlin work?
VietMX Staff asked 3 years ago

In an ordinary generic function like myGenericFun, you can’t access the type T because it is, like in Java, erased at runtime and thus only available at compile time. Therefore, if you want to use the generic type as a normal Class in the function body you need to explicitly pass the class as a parameter like the parameter c in the example.

fun <T> myGenericFun(c: Class<T>)

By marking a type as reified, we’ll have the ability to use that type within the function.

As for a real example, in Java, when we call startActivity, we need to specify the destination class as a parameter. The Kotlin way is:

inline fun <reified T : Activity> Activity.startActivity() {
    startActivity(Intent(this, T::class.java))
}

You can only use reified in combination with an inline function. Such a function makes the compiler copy the function’s bytecode to every place where the function is being used (the function is being “inlined”). When you call an inline function with reified type, the compiler knows the actual type used as a type argument and modifies the generated bytecode to use the corresponding class directly. Therefore calls like myVar is T become myVar is String (if the type argument were String) in the bytecode and at runtime.