Sohum Sachdev Sohum Sachdev - 2 months ago 19
Scala Question

Scala options pattern matching alternatives?

I've been coding on Scala for 2 years and I use a lot of Option's in my code. I feel it is very clear, easy to understand and can easily be treated. This is a normal approach:

val optString = Some("hello")

optString match {
case Some(str) => //do something here!
case None => //do something here
}


I thought that this was the best way to treat Scala Options, but I want to ask if there's a better way to do so?

Answer Source

It really depends on the use case. A general pattern I take when I have an option and I need either to apply an operation to Some or None which yield the same value is to use Option.fold:

val opt = Some(1)
val res: Int = opt.fold(0)(existing => existing + 1)

If you don't like fold, map and getOrElse will do that same trick in reverse:

val res: Int = opt.map(_ + 1).getOrElse(0)

If I want to continue inside the Option container, map does the trick.