Interview frequency: …
Short answer
It retains the actual type information (generics) at runtime thanks to merging the code at the call site through an inline function.
Explanation
Because of JVM limitations, generic type information is erased at compile time (type erasure), so you cannot check T::class.java or T is String directly. Thanks to inline with reified, the compiler copies the actual code and substitutes T with the real type at the call directly in the bytecode, which enables type checks and starting activities without manually passing Class<T>.
Code example
// Without reified
fun <T> start(context: Context, clazz: Class<T>) = Intent(context, clazz)
// With inline and reified
inline fun <reified T : Activity> Context.launchActivity() {
val intent = Intent(this, T::class.java)
startActivity(intent)
}
// Clean call:
context.launchActivity<MainActivity>()Common mistakes
- Trying to use reified in regular functions that are not inline.
- Trying to call a function containing reified from old Java code (not supported because Java does not understand inlining).