Search code examples
scaladictionarycollections

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


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?


Solution

  • 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 so shorter but maybe slightly less confusing than if (...) Map(...) else List(...).