Null-safe Nested Map Navigation

Is there an idiomatic way of doing null-safe navigation through nested maps?

I am trying to move our guys to Kotlin from a lot of Groovy transformations involving JSONs (and no POJOs/POGOs/Data classes). So far it was natural to do something like this in Groovy (but usually a lot more complicated expression):

json?.parent?.child

You can imagine what nightmare that is in Java. Is there a concise and readable way of doing this in Kotlin?

1 Like

I think it is

json[parent]?.get(child)

https://kotlinlang.org/docs/reference/null-safety.html#safe-calls

2 Likes

I know it’s idiomatic, but I find I dislike someMap?.get(e). It seems inconsistent with using someMap[e] for the non-nullable case. I’d kinda like to see something like:

someMapOrNull?[e]

It feels a bit more “regular” in that the syntax is the same as non-nullable reference, just with the ? added…

3 Likes

yeah, I would like to have it with maps

val map: Map<String, Map<String…>>?

map?[“a”]?[“b”]?[“c”] // would be very cool to have
1 Like