Jim
Jim

Reputation: 4425

Adding the contents of a hashmap during hashmap creation

Is there a way to conditionally add the contents of a hashmap to another hashmap during the creation of the hashmap?
E.g. something like:

map.putAll(
   a to b,
   b to c,
   if(otherHashMap != null) otherMap else emptyMap()    
)

I am not sure how the syntax would be. Ideally if the otherMaps is empty I would prefer nothing to be added

)

Upvotes: 1

Views: 99

Answers (2)

You may convert otherHashMap into an array of Pairs and pass them with other pairs using spread operator:

val map = hashMapOf(
    a to b,
    b to c,
    *(otherHashMap?.toList()?.toTypedArray() ?: emptyArray())
)

Another option (without extra objects creation)

val map = hashMapOf(a to b, b to c).apply { putAll(otherHashMap ?: emptyMap()) }

Upvotes: 2

somethingsomething
somethingsomething

Reputation: 2199

There's no such thing as far as I know, but I don't see why you'd need to since it isn't any shorter than the regular syntax:

val map = mutableMapOf(
   a to b,
   b to c,
)
otherHashMap?.let(map::putAll)

Upvotes: 0

Related Questions