16 Şubat 2021
Updated on 24 Temmuz 2024
Kotlin Generics and nullable Class type
Jenerik Tipler
article cover

You need to change Class<I> to Class<out I>:

kotlin
fun <I> calculateStuff(valueType: Class<out I>, defaultValue: I): I {
return defaultValue;
}

You can also do this using reified type parameters:

kotlin
inline fun <reified I> calculateStuff(defaultValue: I): I {
// do some work
return defaultValue;
}

Usage:

kotlin
val myVar1 = calculateStuff("") // myVar1 is String
val myVar2 = calculateStuff<String?>(null) // myVar2 is String?
Subscribe to the newsletter
Get emails from me about web development, tech, and early access to new articles.
Be the first to know when the blog is published
;