Kotlin: conditional items during map creation

One way to do that is to use listOfNotNull(...) + .toMap() and put nulls where you want to skip an item:

val map = listOfNotNull(
   "key1" to var1,
   "key2" to var2,
   if (var3 > 5) "key3" to var3 else null
).toMap()

You can additionally use .takeIf { ... }, but note that it will evaluate the pair regardless of the condition, so if the pair expression calls a function, it will be called anyway:

val map = listOfNotNull(
    /* ... */
    ("key3" to var3).takeIf { var3 > 5 }
).toMap()

Update: Kotlin 1.6 introduced a map builder (buildMap). You can use it like this:

val map = buildMap<Char, Int>() {
   put('a', 1)
   put('b', 2)
   if(var3 > 5) { put('c', 3) }
}

You can use the spread operator * to do that:

val map = mapOf(
   "key1" to var1,
   "key2" to var2,
   *(if(var3 > 5) arrayOf("key3" to var3) else arrayOf())       
)

Tags:

Syntax

Kotlin