Charles Fonseca
Charles Fonseca

Reputation: 140

How to convert nullable MutableMap to not nullable in Kotlin?

How to turn nullable map into not nulllable keeping all keys, mapping all null values to a specific one?

val map = Map<String, Any?> to val map = Map<String, Any>

Upvotes: 2

Views: 1056

Answers (1)

Crafton
Crafton

Reputation: 224

Considering you want to map null values to a specific one, I would suggest you do something like this instead:

 val nonNullMap = map.mapValues { it.value ?: “undefined” }

Where “undefined” is your default value if a null is encountered in your map. If you use the double-bang operator (!!), you will get a KotlinNullPointerException if the value happens to be a null.

Upvotes: 7

Related Questions