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.
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.)
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.
An example of the above:
def find[T](seq: Seq[T], predicate: T => Boolean): Option[T] = {
seq foreach { elem =>
if (predicate(elem)) return Some(elem) // returns from find
}
None
}
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.