Optionally adding items to a Scala Map

前端 未结 3 1319
耶瑟儿~
耶瑟儿~ 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:26

    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)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-02-02 09:47

    How about something along the lines of

    val optional = if(condition) Seq((key3 -> value3)) else Nil
    val entities = Seq(key1 -> value1, key2 -> value2) ++ optional
    val aMap = Map(entities:_*)
    
    0 讨论(0)
提交回复
热议问题