scala闭包/匿名函数中的多个返回点

Deb*_*ski 11 closures scala return-value anonymous-function

据我所知,Scala中没有办法在匿名函数中有多个返回点,即

someList.map((i) => {
    if (i%2 == 0) return i // the early return allows me to avoid the else clause
    doMoreStuffAndReturnSomething(i) // thing of this being a few more ifs and returns
})
Run Code Online (Sandbox Code Playgroud)

提出一个error: return outside method definition.(如果没有提出这个问题,那么代码将不起作用,因为我希望它可以工作.)

我可以做的一个解决方法是以下

someList.map({
    def f(i: Int):Int = {
        if (i%2 == 0) return i
        doMoreStuffAndReturnSomething(i)
    }
    f
})
Run Code Online (Sandbox Code Playgroud)

但是,我想知道是否还有另一种"接受"的做法.也许有可能没有内部功能的名称?

(一个用例是continue在循环中模拟一些有价值的构造.)

编辑

请相信我,有必要避免使用else语句,因为该doMoreStuff部分可能看起来像:

val j = someCalculation(i)
if (j == 0) return 8
val k = needForRecalculation(i)
if (k == j) return 9
finalRecalc(i)
...
Run Code Online (Sandbox Code Playgroud)

当你只有一个if- else结构可用时很容易搞砸了.

当然,在我刚开始给出的简单例子中,它更容易使用else.对不起,我觉得这很清楚.

sbl*_*ndy 5

如果你的匿名函数那么复杂,我会更清楚.匿名函数不适用于比几行更复杂的东西.您可以通过在using方法中声明它来使其成为私有方法

def myF(i:Int):Int = {
    if (i%2 == 0) return i
    doMoreStuffAndReturnSomething(i)
}
someList.map(myF(_))
Run Code Online (Sandbox Code Playgroud)

这是您的变通方法的变体,但更清洁.它们都将其保密为本地方法范围.


Deb*_*ski 1

我认为匿名函数中返回点的主要问题是匿名函数可能会出现在人们通常不会\xe2\x80\x99 期望的地方。因此,\xe2\x80\x99 并不清楚 return 语句实际上属于哪个闭包。通过明确要求def\xe2\x80\x94return*对应关系可以解决此问题。

\n\n

或者,需要在要返回的语句周围有警卫。breakable\xe2\x80\x94break但不幸的是不能\xe2\x80\x99t 返回一个值。一些基于延续的解决方案将能够实现该目标,尽管我\xe2\x80\x99d喜欢等待一些普遍接受和那里的库。

\n