是否有理由避免返回语句 [英] 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.
避免那些显式的返回语句有什么好处吗?
Is there any benefit in avoiding those explicit return statements?
推荐答案
一个return
可能是通过抛出异常来实现的,所以可能有em> 与声明方法结果的标准方式相比有一定的开销.(感谢 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.)
此外,闭包上的 return
将从定义闭包的方法返回,而不仅仅是从闭包本身返回.这使得它既有用,又无用从闭包返回结果.
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)) return Some(elem)
是实现 Function1
并传递给 foreach 的匿名对象的方法
apply
作为参数.去掉 return
就不行了.
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屋!