Kotlin Conditional Map Initialization

May 15, 2019

listOfNotNull

val name = "Desmond"
val age = 40
val map = listOfNotNull(
    "greeting" to "Hello",
    if (name != null) "name" to name else null,
    if (name != null) "nameCapitalize" to name.capitalize() else null,
    if (age != null) "age" to age else null
).toMap()

NOTE: There is some runtime overhead as we need to create a list, filter the list for not null and convert it to a map

Coventional Solution

val map = mutableMapOf<String, Any>(
    "greeting" to "Hello"
)
if (name != null) {
    map["name"] = name
    map["nameCapitalize"] = name.capitalize()
}
if (age != null) {
    map["age"] = age
}

NOTE: Sometimes coventional soltuion is more efficient and flexible.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.