https://kotlinlang.org logo
Title
d

diego-gomez-olvera

03/22/2023, 10:33 AM
I find curious that this code works
fun <T> getClass(type: T): Class<out T> {
    if (type != null) {
        return getClass(type)
    } else {
        error("Unexpected")
    }
}
private fun <T: Any> getClass(type: T) = type::class.java
but if I inline the second method
fun <T> getClass(type: T): Class<out T> {
    if (type != null) {
        return type::class.java // Compilation error
    } else {
        error("Unexpected")
    }
}
the smart cast fails
Expression in a class literal has a nullable type 'T', use !! to make the type non-nullable
s

Sam

03/22/2023, 10:42 AM
d

diego-gomez-olvera

03/22/2023, 10:48 AM
indeed