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 #
.

+3


source to share


4 answers


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.

+6


source


There are many options (pun intended), but for understanding, I think it is most convenient in the case of chains



for { 
  x <- xOpt
  y <- someFunctionReturningOption(x)
  z <- anotherFunctionReturningOption(y)
} yield z

      

+4


source


You are looking for flatMap

:

foo.flatMap(someFunctionReturningOption)

      

This fits into the general monadic structure, where to wrap the type monad is used flatMap

to return the same type (e.g. flatMap

on Seq[T]

returns a Seq

).

+2


source


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

      

+2


source







All Articles