Donuts
Donuts

Reputation: 2241

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.

Upvotes: 0

Views: 1213

Answers (4)

som-snytt
som-snytt

Reputation: 39577

You don't say what foo is, but given

scala> def foo(ps: (String, String)*) = ps.size
foo: (ps: (String, String)*)Int

then

scala> def myFunction(somethingA: String, somethingB: Option[String]): Int =
     | foo(List(Some("A"->somethingA), somethingB.map("B"->_)).flatten: _*)
myFunction: (somethingA: String, somethingB: Option[String])Int

may be what you intend.

Upvotes: 2

cmbaxter
cmbaxter

Reputation: 35443

You could also try folding the Option if you are using Scala 2.10:

val result = somethingB.fold(foo("somethingA" -> somethingA))(b => foo("somethingA" -> somethingA, "somethingB" -> b))

Upvotes: 1

gzm0
gzm0

Reputation: 14842

My 2 cents:

val a = "somethingA" -> somethingA

somethingB.map{ b =>
   foo(a, "somethingB" -> b) 
}.getOrElse { foo(a) }

Hardly more readable. Btw. I don't think you can change the call binding depending on a value :(

Upvotes: 0

om-nom-nom
om-nom-nom

Reputation: 62835

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)
}

Upvotes: 2

Related Questions