I am looking for an idiomatic solution to this problem.
I am building a val Scala (immutable) Map and would like to optionally add one or more items:
val aMap =
Map(key1 -> value1,
key2 -> value2,
(if (condition) (key3 -> value3) else ???))
How can this be done without using a var? What should replace the ???? Is it better to use the + operator?
val aMap =
Map(key1 -> value1,
key2 -> value2) +
(if (condition) (key3 -> value3) else ???))
One possible solution is:
val aMap =
Map(key1 -> value1,
key2 -> value2,
(if (condition) (key3 -> value3) else (null, null))).filter {
case (k, v) => k != null && v != null
}
Is this the best way?