A reified type parameter makes the actual type argument available at runtime inside an inline Kotlin function. It solves a practical limit of JVM type erasure: ordinary generic classes and functions cannot inspect a type parameter such as T at runtime. section 11.0 section 11.2
Checking a caller’s type argument
```kotlin inline fun <reified T> isA(value: Any) = value is T println(isA<String>("abc")) // true println(isA<String>(123)) // false ``` `reified` permits `value is T`. At each call site, inlining gives the compiler the concrete type, so `isA<String>` can effectively use a check against `String`. The same check in a regular generic function fails because T is erased. section 11.2.2
Listing 11.9 A simplified implementation of filterIsInstance
inline fun <reified T> #1
Iterable<*>.filterIsInstance(): List<T> {
val destination = mutableListOf<T>()
for (element in this) {
if (element is T) { #2
destination.add(element)
}
}
return destination
}
This compact implementation shows the common pattern: iterate values, test each element with `is T`, and collect the matching values as `List<T>`. Calling `filterIsInstance<String>()` selects only strings while preserving a useful return type. section 11.2.2
Reification is especially useful for APIs that otherwise require a class token. A wrapper around Java’s `ServiceLoader` can accept `loadService<Service>()` instead of `ServiceLoader.load(Service::class.java)`, while still obtaining `T::class.java` internally. The same technique can target an Android `Activity` or expose an inline extension property based on a generic receiver’s class. section 11.2.3 section 11.2.4
Wrapping a Java Class-based API
```kotlin inline fun <reified T> loadService() = ServiceLoader.load(T::class.java) val service = loadService<Service>() ``` The caller supplies the desired class as a type argument; the implementation converts that argument to the required `java.lang.Class` value. section 11.2.3
A reified parameter supports selected runtime operations, but it is not a general mechanism for constructing or controlling an unknown type.
- Use it in type checks and casts: `is`, `!is`, `as`, and `as?`. section 11.2.5
- Obtain class representations through `::class` and `::class.java`, including for reflection and Java APIs. section 11.2.5
- Pass it as a type argument to another function. section 11.2.5
- Do not use it to create an instance, call companion-object methods, reify a class parameter or non-inline function parameter, or forward a non-reified parameter to a reified call. section 11.2.5
Because reification depends on inline expansion, marking a parameter `reified` also makes the enclosing function inline. Its lambdas are therefore inlined unless they are marked `noinline`. For deserialization, an inline `deserialize<T>()` can receive the target object type at runtime, while parsing and reflection handle the work of producing that object. section 11.2.5 section 12.2.4
