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?

I think it is

json[parent]?.get(child)

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

1 Like

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…

1 Like