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?
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
orNone
which yields the same value is to useOption.fold
:If you don't like
fold
,map
andgetOrElse
will do that same trick in reverse:If I want to continue inside the
Option
container,map
does the trick.