I know the fact that a Some object can be a None or one of the objects I passed. What is the ideal way of extracting a field from the Some object given the fact that it is not None? I have made a class 'At' that has 'date' as one of its fields. Since the Some class has a mixin with Product trait, the following works fine:
(An object with return type Some(At)).productElement(0).asInstanceOf[At].date
But is there an ideal way to do this?
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)