从 Scala 中的 Some 中提取字段

Cor*_*ped 3 scala scala-option

我知道 Some 对象可以是 None 或我传递的对象之一。鉴于它不是 None 的事实,从 Some 对象中提取字段的理想方法是什么?我制作了一个“At”类,它的字段之一是“日期”。由于 Some 类具有与 Product 特征的混合,因此以下工作正常:

(An object with return type Some(At)).productElement(0).asInstanceOf[At].date
Run Code Online (Sandbox Code Playgroud)

但是有没有一种理想的方法来做到这一点?

dre*_*xin 7

有几种安全的使用方法Option。如果您想检索包含的值,我建议您使用fold,getOrElse或模式匹配。

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 =>
}
Run Code Online (Sandbox Code Playgroud)

如果要修改的值,并把它传递到别的地方,而不从提取它Option,你可以使用mapflatMapfilter / 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)
Run Code Online (Sandbox Code Playgroud)

或者如果你想执行一个副作用,你可以使用 foreach

opt foreach println

for (x <- opt) println(x)
Run Code Online (Sandbox Code Playgroud)

  • 我想我们应该将所有方法组合在一个答案中。你会在你的答案中添加`match`、`map` + `getOrElse`、`for-comprehension`(有和没有`yield`)、`foreach` 等等吗? (2认同)