// Created on savesnippets.com · https://savesnippets.com/CKorQ41Y1YmG0E import kotlin.reflect.KClass // Without reified — caller has to pass the class explicitly fun firstOfType(items: List, klass: KClass): T? { return items.firstOrNull { klass.isInstance(it) } as T? } // With reified — call site just says firstOf(items) inline fun firstOf(items: List): T? = items.firstOrNull { it is T } as T? fun main() { val mixed: List = listOf(1, "hi", 2.5, "bye", true) println(firstOfType(mixed, String::class)) // "hi" (verbose call site) println(firstOf(mixed)) // "hi" (clean!) println(firstOf(mixed)) // 2.5 println(firstOf(mixed)) // null // Common real-world: type-safe JSON parsing // inline fun Gson.fromJson(s: String): T = // fromJson(s, T::class.java) }