0

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
Donuts
  • 2,185
  • 3
  • 20
  • 31

4 Answers4

2

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)
}
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
2

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.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
1

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))
cmbaxter
  • 35,283
  • 4
  • 86
  • 95
0

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 :(

gzm0
  • 14,752
  • 1
  • 36
  • 64