Extract fields from some in Scala

I know that some object may be None or one of the objects that I passed. What is the ideal way to extract a field from a Some object, given the fact that it is not None? I created an "At" class that has a "date" as one of its fields. Since the Some class has a mixin with the Product attribute, the following works just fine:

(An object with return type Some(At)).productElement(0).asInstanceOf[At].date

But is there an ideal way to do this?

+1
source share
2 answers

There are several safe ways to work with Option. If you want to contain the value, I suggest you use either fold, getOrElseor 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 =>
}

, Option, map, flatMap, filter / withFilter .. , , -:

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)

, , foreach

opt foreach println

for (x <- opt) println(x)
+4

:

1) get. , 300% , . java.util.NoSuchElementException: None.get.

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

2) , "map":

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

:

option map { at => myMethod(at.date) } 
0

All Articles