Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the idiomatic way to do a map/getOrElse returning Unit in Scala?

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

like image 547
Olivier Bruchez Avatar asked Nov 07 '12 10:11

Olivier Bruchez


People also ask

What does MAP return in Scala?

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.

How does getOrElse work in Scala?

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.

How do you access map elements in Scala?

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.

What is Scala mapValues?

mapValues creates a Map with the same keys from this Map but transforming each key's value using the function f .


2 Answers

What Kim Stebel said: pattern matching is a simple solution.

valueOption match {
  case Some(value) => doSideEffectA(value)
  case None => doSideEffectB()
}
like image 194
pr1001 Avatar answered Oct 24 '22 21:10

pr1001


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
like image 35
Rex Kerr Avatar answered Oct 24 '22 22:10

Rex Kerr