Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some reason to avoid return statements

Tags:

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?

like image 222
opensas Avatar asked Sep 08 '12 21:09

opensas


People also ask

Do you always need a return statement?

NO, a function does not always have to have an explicit return statement. If the function doesn't need to provide any results to the calling point, then the return is not needed. However, there will be a value of None which is implicitly returned by Python.

Which functions should not use a return statement?

In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.

Is it optional to use return statement?

The RETURN statement is optional and it can be absent from a function. If there is no RETURN statement, a function will be terminated, when 4GL encounters the END FUNCTION keywords and the program control will be passed to the calling routine.

Do All methods need a return statement?

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.


1 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.

like image 159
Daniel C. Sobral Avatar answered Sep 18 '22 15:09

Daniel C. Sobral