Is there some reason to avoid return statements

后端 未结 3 1009
生来不讨喜
生来不讨喜 2021-02-04 01:14

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.

3条回答
  •  佛祖请我去吃肉
    2021-02-04 01:57

    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.

提交回复
热议问题