Optionally adding items to a Scala Map

前端 未结 3 1318
耶瑟儿~
耶瑟儿~ 2021-02-02 09:01

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:

<
3条回答
  •  不知归路
    2021-02-02 09:39

    You can add directly to the map:

    scala> val map = Map(1 -> 2, 3 -> 4)
    scala> val some = Some(5 -> 6)
    scala> val none = None
    scala> val combinedMap = map ++ some ++ none
    combinedMap: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4, 5 -> 6)
    

提交回复
热议问题