for-yield-getOrElse 是典型的 Scala 还是有更好的方法? [英] Is for-yield-getOrElse paradigmatic Scala or is there a better way?

查看:40
本文介绍了for-yield-getOrElse 是典型的 Scala 还是有更好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想提取一堆选项 a、b 等.这是在 Scala 中执行此操作的最佳方法吗?括号中的 for-yield 对我来说看起来有点混乱.

Basically I want to extract a bunch of Options a, b, etc. Is this the best way to do this in Scala? It looks kind of confusing to me to have the for-yield in parenthesis.

(for {
  a <- a
  b <- b
  c <- c
  ...
} yield {
  ...
}) getOrElse {
  ...
}

推荐答案

尝试使用 mapflatMap 代替.假设您有以下类层次结构:

Try using map and flatMap instead. Assume you have the following class hierarchy:

case class C(x: Int)
case class B(c: Option[C])
case class A(b: Option[B])

val a = Some(A(Some(B(Some(C(42))))))

为了提取42,你可以说:

a.flatMap(_.b).flatMap(_.c).map(_.x).getOrElse(-1)

这大致相当于:

for(
  a <- a
  b <- a.b
  c <- b.c)
      yield c.x

除了它返回Some(42).事实上,for 理解实际上被翻译成一系列map/flatMap 调用.

except that it returns Some(42). In fact for comprehension is actually translated into a sequence of map/flatMap calls.

这篇关于for-yield-getOrElse 是典型的 Scala 还是有更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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