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 two ways:
1) You can use 'get' method. But you should use only if you are 300% sure that there wouldn't be None. As you will get
java.util.NoSuchElementException: None.get
.2) As Option is a monad you can use 'map' method:
or you can use it:
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