gpt4 book ai didi

function - Scala 函数文字中的 `return`

转载 作者:行者123 更新时间:2023-12-05 08:58:13 24 4
gpt4 key购买 nike

我正在尝试做这样的事情:

var fun : (Int,Int) => Double = (a,b) =>
{
// do something
return 1.0
}

但是,我的 IDE 提示 Return 语句在方法定义之外。那么我如何在 Scala 的函数字面量中显式地给出 return 语句呢?

最佳答案

在 Scala 中,return 语句从封闭的方法体中返回。如果 return 出现在函数字面量内,则它是通过抛出异常来实现的。 return 将在函数内部抛出一个异常,然后该异常将被封闭方法捕获。 Scala 以这种方式工作,以便使用使函数不可见的自定义控件结构,例如:

def geometricAverage(l: List[Double]): Double = {
val product = l.foldLeft(1.0) { (z, x) =>
if (x == 0) return 0 else z * x
}
Math.pow(product, 1.0 / l.length)
}

此示例中的 returngeometricAverage 方法返回,允许它在找到 0 时立即完成。您不需要知道 foldLeft 是一种采用函数而不是内置构造来实现这一点的方法。

Scala 的偏好是以函数式风格编写函数,利用 Scala 面向表达式的特性使 return 变得不必要。例如:

val fun: (Int,Int) => Double = (a,b) => {
if (a == b) {
// side effect here, if desired
0.0
} else {
// side effect here, if desired
1.0
}
}

如果你真的想在函数的定义中使用return,你可以手动实现合适的函数接口(interface)而不是使用函数字面量:

val fun = new Function2[Int, Int, Double] {
def apply(x: Int, y: Int): Double = {
if (x == y)
return 0.0
1.0
}
}

但这不是惯用的,强烈建议不要这样做。

关于function - Scala 函数文字中的 `return`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24856106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com