NavigableMap and null management

Hi all,

I’ve just ran into a NullPointerException in Java Interop code (playing with treemaps), and asked myself if someone has good advice to share. Searching around Google did not helped me much.

My problem : I’m using a NavigableMap typed with non-nullable key/values, and non-nullability also applies on return types of search functions. It looks dangerous to me, because a map containing only non-null values does not mean that searches are always successful on it (out of range, empty map, etc.). Now, I see that Map interface has no such problem, as (in my understanding) Kotlin stdlib has made its own override. However, I cannot find a pure Kotlin equivalent for NavigableMap specialization.

Does anyone know a full Kotlin equivalent of java TreeMap ? Or is there a workaround to prevent insertion of null keys/values without losing null safety on various search methods (lastEntry, floorKey, etc.) ?

Here’s a sample of code to illustrate my problem. In REPL, no compiler error arise, but only an IllegalStateException at execution :

val myMap = TreeMap<Long, String>()
myMap[1] = "1"

// This compile, but will return a null value anyway, causing a NullPointerException later 
val searchedKey : Long = myMap.floorKey(0)

Regards,

The problem is that you are dealing with platform types. The return type of TreeMap<Long, String>.floorKey is Long! so kotlin will just accept your claim that it is not nullable.
You should change your code to

val searchedKey : Long? = myMap.floorKey(0)

or let the compiler auto detect the type. In either case you are able to perform null checks now.

1 Like

Thank you for the quick answer.

I’ve read the related documentation, I understand now :slight_smile: