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 NullPointerException
s 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.
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".