Is there a way to do something like this in Kotlin?
mapOf(
"key1" to var1,
"key2" to var2,
if(var3 > 5) "key3" to var3
)
Or the only way is to add the key "key3" after the map is created? I'd like to add an item to a map only if some condition is met.
One way to do that is to use listOfNotNull(...)
+ .toMap()
and put null
s 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()