Home > Net >  Add keys conditionally in Scala to a Map[String,String]?
Add keys conditionally in Scala to a Map[String,String]?

Time:12-15

I want to add keys as shown below:

val x = false
  val y = Map[String,String](
    "name" -> "AB",
    if(x) "placement"->"pc" else null
  )
  println(y)

Note that its an immutable map, this works when x is true but throws runtime error when x is false, I tried to put else Unit but that doesn't work as well.

Can someone point me the most elegant as well as optimized syntax to do so?

CodePudding user response:

Sorted it like this:

val x = true
  val y = Map[String,String](
    "name" -> "AB"
  )    (if(x) Map[String,String]("place"->"pc") else Nil)

still wondering if this is good or something better should be used.

CodePudding user response:

One more option is

val y = Map[String, String](
  Seq("name" -> "AB")   
    (if (x) Seq("placement" -> "pc") else Seq()): _*
)

or

val y = (Seq("name" -> "AB")   
  (if (x) Seq("placement" -> "pc") else Seq())).toMap

or

val y = (Seq("name" -> "AB")   
  Option.when(x)("placement" -> "pc").toSeq).toMap

This is not shorter but maybe a little less confusing than if (...) Map(...) else List(...).

  • Related