Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
Tomas Karlsson Avatar asked Mar 09 '17 21:03

Tomas Karlsson


People also ask

How does Kotlin check not null?

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.

What is mapNotNull?

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.

Can map hold null values?

Values entered in a map can be null .


2 Answers

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?
like image 65
Nurlan Avatar answered Sep 18 '22 22:09

Nurlan


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.

like image 32
Rafal G. Avatar answered Sep 20 '22 22:09

Rafal G.