Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does HashMap.get not return a nullable type?

I was a bit surprised that the following example throws a NullPointerException:

fun main(args: Array<String>) {
    val hm = HashMap<String, Int>()
    hm.put("alice", 42)
    val x = hm.get("bob")
    println(x)   // BOOM
}

I thought there are no NullPointerExceptions in Kotlin code?

If I annotate x with an optional type, the programm prints null instead:

fun main(args: Array<String>) {
    val hm = HashMap<String, Int>()
    hm.put("alice", 42)
    val x: Int? = hm.get("bob")
    println(x)   // null
}

Have I discovered a special case, or is this a general problem with Kotlin/Java interop?

I am using IntelliJ IDEA 14.1 Community Edition with Kotlin 0.11.91.1 plugin.

like image 358
fredoverflow Avatar asked Jun 11 '26 06:06

fredoverflow


1 Answers

Your variable hm is of type HashMap and because that's a platform class its methods return platform types. Kotlin's own Map and its subtrait subinterface MutableMap however return nullable types for get().

Change your code to

val hm : MutableMap<String, Int> = HashMap()

and it will print "null".

like image 129
Kirill Rakhman Avatar answered Jun 13 '26 06:06

Kirill Rakhman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!