scaladictionaryconditional-statementsscala-option

How do I rewrite this conditional with an option in Scala in a cleaner way?


Is there a cleaner way of writing this in scala?

def myFunction(somethingA: String, somethingB: Option[String]): Unit =
  if (somethingB.isDefined) 
    foo("somethingA" -> somethingA, "somethingB" -> somethingB.get) 
  else
    foo("somethingA" -> somethingA)

I was thinking something along the lines of:

def myFunction(somethingA: String, somethingB: Option[String]): Unit =
  foo("somethingA" -> somethingA, somethingB.map("somethingB" -> _).getOrElse(.... pleh ....))

But even if I replace the ".... pleh ...." part with some kind of expression, i don't want it to even add the mapping if somethingB isn't defined. So I don't envision that remotely working. Not sure what the right solution is.


Solution

  • Not much cleaner:

    def myFunction(somethingA: String, somethingB: Option[String]): Unit = somethingB match {
      case Some(b) => foo("somethingA" -> somethingA, "somethingB" -> b)
      case None    => foo("somethingA" -> somethingA)
    }