有什么理由避免返回语句 [英] Is there some reason to avoid return statements
问题描述
有时我会看到大量的Scala代码,其中包含嵌套的多个级别的条件和匹配项,使用显式返回以退出该函数会更加清楚。
Sometimes I see chunks of Scala code, with several nested levels of conditionals and matchings, that would be much clearer using an explicit return to exit from the function.
避免那些显式的return语句有什么好处?
Is there any benefit in avoiding those explicit return statements?
推荐答案
A return
可以通过抛出异常来实现,因此它在声明方法结果的标准方法上可能具有一定的开销。 (感谢Kim Stebel指出这种情况并不总是,甚至可能不是经常如此。)
A return
may be implemented by throwing an exception, so it may have a certain overhead over the standard way of declaring the result of a method. (Thanks for Kim Stebel for pointing out this is not always, maybe not even often, the case.)
此外,返回$闭包上的c $ c>将从定义闭包的方法 中返回,而不仅仅是从闭包本身中返回。
Also, a return
on a closure will return from the method in which the closure is defined, and not simply from the closure itself. That makes it both useful for that, and useless for returning a result from closures.
上面的示例:
def find[T](seq: Seq[T], predicate: T => Boolean): Option[T] = {
seq foreach { elem =>
if (predicate(elem)) return Some(elem) // returns from find
}
None
}
如果您仍然不理解,请 elem => if(predicate(elem))返回Some(elem)
是实现 Function1的匿名对象的方法
并作为参数传递给 apply
foreach
。从其中删除返回
,它将不起作用。
If you still don't understand, elem => if (predicate(elem)) return Some(elem)
is the method apply
of an anonymous object of that implements Function1
and is passed to foreach
as parameter. Remove return
from it, and it won't work.
这篇关于有什么理由避免返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!