如何在 Scala 中组合选项值? [英] How to combine Option values in Scala?
本文介绍了如何在 Scala 中组合选项值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够应用一个操作 f: (T,T) =>Scala 中的 T
到 Option[T]
值.如果两个值中的任何一个为 None
,我希望结果为 None
.
I want to be able to apply an operation f: (T,T) => T
to Option[T]
values in Scala. I want the result to be None
if any of the two values is None
.
更具体地说,我想知道是否有更短的方法来执行以下操作:
More specifically, I want to know if there is a shorter way to do the following:
def opt_apply[T](f: (T,T) => T, x: Option[T], y: Option[T]): Option[T] = {
(x,y) match {
case (Some(u),Some(v)) => Some(f(u,v))
case _ => None
}
}
我试过 (x zip y) map {case (u,v) =>f(u,v)}
但结果是 Iterator[T]
而不是 Option[T]
.
I have tryied (x zip y) map {case (u,v) => f(u,v)}
but the result is an Iterator[T]
not an Option[T]
.
推荐答案
scala> val (x, y) = (Some(4), Some(9))
x: Some[Int] = Some(4)
y: Some[Int] = Some(9)
scala> def f(x: Int, y: Int) = Math.max(x, y)
f: (x: Int,y: Int)Int
scala> for { x0 <- x; y0 <- y } yield f(x0, y0)
res26: Option[Int] = Some(9)
scala> val x = None
x: None.type = None
scala> for { x0 <- x; y0 <- y } yield f(x0, y0)
res27: Option[Int] = None
这篇关于如何在 Scala 中组合选项值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文