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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.