Template for combining calls that are used in parameters
I find that I often find myself needing to combine functions that work with Option
and return another Option
that looks something like this:
if(foo.isDefined) someFunctionReturningOption(foo.get) else None
Is there a cleaner way to do this? This pattern gets quite verbose with more complex variables.
I can see that this is a fair bit in the form processing code to deal with optional data. It will insert None
if value None
or some kind of conversion (which could potentially fail) if there is some value.
This is very similar to the operator ?.
suggested for C # .
source to share
You can use flatMap
:
foo.flatMap(someFunctionReturningOption(_))
Or for understanding:
for {
f <- foo
r <- someFunctionReturningOption(f)
} yield r
For understanding, it is preferable to combine several instances of these functions together with the fact that they are de-saccharified to flatMap
s.
source to share
Option
supports map (), so when x
is Option[Int]
this construct:
if (x.isDefined)
"number %d".format(x.get)
else
None
easier to write as:
x map (i => "number %d".format(i))
the map will keep None
unmodified, but will apply the function you pass to it to whatever value, and put the result back into the option. For example, notice how "x" is converted to the string message below, but "y" is passed as None
:
scala> val x: Option[Int] = Some(3)
x: Option[Int] = Some(3)
scala> val y: Option[Int] = None
y: Option[Int] = None
scala> x map (i => "number %d".format(i))
res0: Option[String] = Some(number 3)
scala> y map (i => "number %d".format(i))
res1: Option[String] = None
source to share