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 eitherfold
,getOrElse
or pattern matching.If you want to modify the value and pass it on to somewhere else without extracting it from the
Option
, you can usemap
,flatMap
,filter / withFilter
etc. and therefore also for-comprehensions:Or if you want to perform a side-effect, you can use
foreach