Skip to content

Reified generics

Reified Generics Deep Dive

Overview

Reified generics are one of Kotlin's most interview-worthy features because they connect language syntax to JVM type erasure and compiler inlining.


Core Concepts

Normally, JVM generics are erased at runtime.

Kotlin solves some of that limitation with reified type parameters in inline functions:

inline fun <reified T> Any.isType(): Boolean = this is T

Internal Implementation

Because the function is inlined, the compiler can substitute real type checks at the call site.

That is why this is possible only inside inline functions.


JVM / Compiler Behavior

Without reified support, this is not possible safely:

fun <T> check(value: Any): Boolean {
    // cannot use `is T` here normally
    return false
}

With reified:

inline fun <reified T> check(value: Any): Boolean = value is T

Code Examples

inline fun <reified T> Gson.fromJsonTyped(json: String): T {
    return fromJson(json, T::class.java)
}

Common Interview Questions

  • Q: Why does reified require inline? A: Connect Kotlin features to outcomes: safer APIs through nullability, clearer state modeling, and awareness of generated bytecode and allocation cost.
  • Q: How does it relate to type erasure? A: Tie Kotlin language features to production outcomes: safety, readability, testability, and runtime or allocation tradeoffs when relevant.
  • Q: When is reified more useful than reflection? A: Connect Kotlin features to outcomes: safer APIs through nullability, clearer state modeling, and awareness of generated bytecode and allocation cost.

Production Considerations

Reified generics improve API ergonomics, but still depend on JVM/runtime limits. They are especially useful for utility libraries and framework helpers.


Performance Insights

The main tradeoff is still inline-related bytecode duplication, not magic runtime cost.


Senior-Level Insights

Strong answers connect reified generics to compiler substitution, not just β€œKotlin can access generic types at runtime.” The mechanism matters.