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)
}
Create a free account and build your private vault. Share publicly whenever you want.