androidengineers.Book a session

Generics and Type Parameters

Reified Type Parameters & inline

article15 minMedium

Reified parameters support selected runtime checks

An inline function with reified T can refer to its type parameter in operations such as is T and T::class. The call site supplies the concrete type when code is inlined.

inline fun <reified T> matching(values: List<Any?>): List<T> =
    values.filterIsInstance<T>()

fun main() {
    check(matching<String>(listOf("Kotlin", 25, null)) == listOf("Kotlin"))
}

Reification does not recursively recover every erased generic argument. A runtime check for a list still cannot prove that all of its elements match a nested type argument. Treat deserialization and nested collection validation separately.

For a public inline function, implementation visibility and binary compatibility deserve attention. Reification is not a reason to inline every generic helper.

Exercise

Create a helper returning the first matching value or null. Test absent matches and multiple matches. Then explain why List<String> requires stronger validation than merely recognizing a runtime list.

Check: the code should not use an unchecked cast to pretend it validated nested elements.

Reference: Reified type parameters

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Reified Type Parameters & inline | Kotlin Core Programming | Android Engineers