我知道 Some 对象可以是 None 或我传递的对象之一。鉴于 Some 对象不是 None 的事实,从 Some 对象中提取字段的理想方法是什么? 我创建了一个“日期”作为其字段之一的“At”类。由于 Some 类有一个具有 Product trait 的 mixin,因此以下工作正常:
(An object with return type Some(At)).productElement(0).asInstanceOf[At].date
但是有没有理想的方法来做到这一点?
最佳答案
有几种安全的方法可以使用 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 =>
}
如果你想修改值并将其传递到其他地方而不从 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)
关于scala - 从Scala中的Some中提取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20700167/