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:
Another possibility is to take advantage of the iterable nature of Option
.
A non-empty value o
:
scala> val o = Some('z' -> 3)
scala> (Seq('x' -> 1, 'y' -> 2) ++ o).toMap
res1: scala.collection.immutable.Map[Char,Int] = Map(x -> 1, y -> 2, z -> 3)
An empty value o
:
scala> val o = None
scala> (Seq('x' -> 1, 'y' -> 2) ++ o).toMap
res2: scala.collection.immutable.Map[Char,Int] = Map(x -> 1, y -> 2)