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?
You can use the "?. let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value.
mapNotNull( transform: (T) -> R? ): List<R> Returns a list containing only the non-null results of applying the given transform function to each element in the original array.
Values entered in a map can be null .
There is another method for getting not null value from map:
fun <K, V> Map<K, V>.getValue(key: K): V
throws NoSuchElementException - when the map doesn't contain a value for the specified key and no implicit default value was provided for that map.
but operator for get == map[] returns nullable.
operator fun <K, V> Map<out K, V>.get(key: K): V?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With