There are several safe ways to work with Option
. If you want to retrieve the contained value, I would suggest you to use either fold
, getOrElse
or pattern matching.
opt.fold { /* if opt is None */ } { x => /* if opt is Some */ }
opt.getOrElse(default)
// matching on options should only be used in special cases, most of the time `fold` is sufficient
opt match {
case Some(x) =>
case None =>
}
If you want to modify the value and pass it on to somewhere else without extracting it from the Option
, you can use map
, flatMap
, filter / withFilter
etc. and therefore also for-comprehensions:
opt.map(x => modify(x))
opt.flatMap(x => modifyOpt(x)) // if your modification returns another `Option`
opt.filter(x => predicate(x))
for {
x <- optA
y <- optB
if a > b
} yield (a,b)
Or if you want to perform a side-effect, you can use foreach
opt foreach println
for (x <- opt) println(x)