Kotlin

reified Type Parameters

admin by @admin ADMIN
Jun 13, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
In an `inline` function, a `reified` type parameter survives erasure — you can use `T::class`, `is T`, `as T` at runtime. The killer use-case for JSON parsers ("give me a List<User>").
Kotlin
Raw
import kotlin.reflect.KClass

// Without reified — caller has to pass the class explicitly
fun <T : Any> firstOfType(items: List<Any>, klass: KClass<T>): T? {
    return items.firstOrNull { klass.isInstance(it) } as T?
}

// With reified — call site just says firstOf<String>(items)
inline fun <reified T> firstOf(items: List<Any>): T? =
    items.firstOrNull { it is T } as T?

fun main() {
    val mixed: List<Any> = listOf(1, "hi", 2.5, "bye", true)

    println(firstOfType(mixed, String::class))    // "hi"   (verbose call site)
    println(firstOf<String>(mixed))                // "hi"   (clean!)
    println(firstOf<Double>(mixed))                // 2.5
    println(firstOf<Long>(mixed))                  // null

    // Common real-world: type-safe JSON parsing
    // inline fun <reified T> Gson.fromJson(s: String): T =
    //     fromJson(s, T::class.java)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.