从 Scala 中的 Some 中提取字段 [英] Extracting field from Some in Scala

查看:54
本文介绍了从 Scala 中的 Some 中提取字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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 =>
}

如果你想修改值并将其传递给其他地方而不从Option中提取它,你可以使用mapflatMapfilter/withFilter 等等,因此也有 for-comprehensions:

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)

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

Or if you want to perform a side-effect, you can use foreach

opt foreach println

for (x <- opt) println(x)

这篇关于从 Scala 中的 Some 中提取字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆