What's the most idiomatic way to do a side-effect if a value is Some(...) and do another side-effect if a value is None. Here's what I'd currently tend to write:
def doSideEffectA(value: Int) {
// ...
}
def doSideEffectB() {
// ...
}
def doSideEffect(valueOption: Option[Int]) {
valueOption map { value =>
doSideEffectA(value)
} getOrElse {
doSideEffectB()
}
}
My problem is that if I didn't have to do anything if valueOption is None, here's what I'd write:
def doSideEffectNothingIfNone(valueOption: Option[Int]) {
valueOption foreach { value =>
doSideEffectA(value)
}
}
map/getOrElse are usually not used in a side-effect context, while foreach is. I'm not really comfortable with valueOption map { ... } getOrElse { ... } returning Unit, as I don't really "get" anything from my Option[Int].
map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.
As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value.
Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.
mapValues creates a Map with the same keys from this Map but transforming each key's value using the function f .
What Kim Stebel said: pattern matching is a simple solution.
valueOption match {
case Some(value) => doSideEffectA(value)
case None => doSideEffectB()
}
Scala 2.10 includes a fold
method on Option
which is suitable for any case where you need both None
and Some
to resolve to the same type (including Unit
):
scala> Option("salmon").fold(println("No fish")){f => println(s"I like $f")}
I like salmon
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With