collectionskotlin

Kotlin Map with non null values


Let say that I have a Map for translating a letter of a playing card to an integer

 val rank = mapOf("J" to 11, "Q" to 12, "K" to 13, "A" to 14)

When working with the map it seems that I always have to make a null safety check even though the Map and Pair are immutable:

val difference = rank["Q"]!! - rank["K"]!!

I guess this comes from that generic types have Any? supertype. Why can't this be resolved at compile time when both Map and Pair are immutable?


Solution

  • It is not about the implementation of Map (being it Kotlin or Java based). You are using a Map and a map may not have a key hence [] operator returns nullable type.