scala - 从Scala中的Some中提取字段

标签 scala scala-option

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

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

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

最佳答案

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

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 中提取它,你可以使用 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)

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

opt foreach println

for (x <- opt) println(x)

关于scala - 从Scala中的Some中提取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20700167/

相关文章:

scala - Zeppelin SqlContext registerTempTable 问题

scala - 需要将 Seq[Option[A]] 转换为 Option[Seq[A]]

scala - Scala 值类的惯用方法

scala - 为什么使用案例类对 JSON 进行编码时会出现错误 "Unable to find encoder for type stored in a Dataset"?

scala - Scala 中的选项 monad

scala - 我如何才能扭转期权莫纳德的潮流?

java - 在 Scala 中使用通用数据类型值定义 Map

database - 如何从 Play2!Scala Anorm 中的选择语句中检索 Option[List[X]] 而不是 List[X]?

scala - 小数据大小与可用内存的执行程序 OutOfMemoryExceptions

json - 将 JSON 文件读入 Spark 数据集并从单独的 Map 添加列