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.
Add and update entries To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map. In sorted maps, the positions of new elements are defined by the order of their keys.
Yes, it will. The reference for mutableMapOf() says: The returned map preserves the entry iteration order.
The basic mapping function is map() . It applies the given lambda function to each subsequent element and returns the list of the lambda results. The order of results is the same as the original order of elements. To apply a transformation that additionally uses the element index as an argument, use mapIndexed() .
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()
Update: Kotlin 1.3 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())
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With