8

I have the following code:

val map = HashMap<Int, Any>()
fun <T> test(t: T) = map.put(0, t) // Type mismatch: inferred type is T but kotlin.Any was expected

But every Kotlin class has Any as a superclass, so why this error?

1 Answer 1

20

T is nullable in this function. You should explicitly specify that it's non-nullable.

fun <T : Any> test(t: T) = map.put(0, t)
1
  • 12
    To add to that, the default bound for a naked <T> is Any?
    – Kiskae
    Apr 20, 2016 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.