Is there some reason to avoid return statements

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?

Answers


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.


Need Your Help

ModelAdmin screen for DataObject not opening

php silverstripe data-objects modeladmin

In SilverStripe 3.1.13 I'm trying to establish a simple one-to-many relationships between DataObjects administrated by ModelAdmin. There is a Facility class that can have one off FacilityCategory.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.