Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: conditional items during map creation

Tags:

syntax

kotlin

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.

like image 559
Aleš Zrak Avatar asked Sep 06 '17 12:09

Aleš Zrak


People also ask

How do I add values to my map in Kotlin?

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.

Does map preserve order Kotlin?

Yes, it will. The reference for mutableMapOf() says: The returned map preserves the entry iteration order.

How does map function work in Kotlin?

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() .


2 Answers

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()
like image 200
hotkey Avatar answered Sep 19 '22 09:09

hotkey


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())       
)
like image 32
Willi Mentzel Avatar answered Sep 20 '22 09:09

Willi Mentzel