Scala options pattern matching alternatives?

1.1k views Asked by At

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?

1

There are 1 answers

4
Yuval Itzchakov On BEST ANSWER

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