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)

其他提示

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.

val option: Option[At] = getAtMethod
val dateField = option.get.date

2) As Option is a monad you can use 'map' method:

val option: Option[At] = ...
val optionalDate: Option[Date] = option map { _.date }

or you can use it:

option map { at => myMethod(at.date) } 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top