netimen
netimen

Reputation: 4419

Type mismatch: inferred type is T but kotlin.Any was expected

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?

Upvotes: 8

Views: 7092

Answers (1)

Michael
Michael

Reputation: 54705

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)

Upvotes: 20

Related Questions