为什么不应该在Scala中使用return?

项目中写了类似逻辑的Scala代码如下,很明显没有按照预期工作。

def foo(): Unit = {
  val numbers = List(1, 2, 3, 2, 1)
  numbers.foreach(num => {
    if (num > 2) return  
    else println(num)
  })
  println("end")
}
foo()
// 输出:
// 1
// 2

如果上面这一段代码翻译为java呢?

public void foo() {
    final List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 1);
    numbers.forEach(num -> {
        if (num > 3) return;
        else System.out.println(num);
    });
    System.out.println("end");
}
// 输出: 
// 1
// 2
// 2
// 1
// end

对比的结果很明显,scala并没有按照“预期”工作,java的运行结果比较符合直觉。Scala在遇到return时,直接将外层的foo方法“截断”并返回了,结果导致foreach的迭代都中断了,运行过程中也没有出现任何错误提示。so, 为什么会这样?

这里直接搬一篇写的比较好的博客,后续有空再翻译 >_>

The Point of No Return

Alright, every time Martin’s Coursera course runs we get people in #scala asking why they get style points taken off for using return. So here’s the pro tip:

The return keyword is not “optional” or “inferred”; it changes the meaning of your program, and you should never use it.

Let’s look at a little example.

// Add two ints, and use this method to sum a list
def add(n:Int, m:Int): Int = n + m
def sum(ns: Int*): Int = ns.foldLeft(0)(add)

scala> sum(33, 42, 99)
res0: Int = 174

// Same, using return 
def addR(n:Int, m:Int): Int = return n + m
def sumR(ns: Int*): Int = ns.foldLeft(0)(addR)

scala> sumR(33, 42, 99)
res1: Int = 174

So far so good. There is no apparent difference between sum and sumR which may lead you to think that return is simply an optional keyword. But let’s refactor a bit by inlining add and addR.

// Inline add and addR
def sum(ns: Int*): Int = ns.foldLeft(0)((n, m) => n + m) // inlined add

scala> sum(33, 42, 99)
res2: Int = 174 // alright

def sumR(ns: Int*): Int = ns.foldLeft(0)((n, m) => return n + m) // inlined addR

scala> sumR(33, 42, 99)
res3: Int = 33 // um.

What the what?
So, the short version is:

A return expression, when evaluated, abandons the current computation and returns to the caller of the method in which return appears.

So in the example above, the return statement in the anonymous function does not return from the function it appears in; it returns from the method it appears in. Another example:

def foo: Int = { 
  val sumR: List[Int] => Int = _.foldLeft(0)((n, m) => return n + m)
  sumR(List(1,2,3)) + sumR(List(4,5,6))
}

scala> foo
res4: Int = 1

Non-Local Return

When a function value containing a return statement is evaluated nonlocally, the computation is abandoned and the result is returned by throwing a NonLocalReturnControl[A]. This implementation detail escapes into the wild without much ceremony:

def lazily(s: => String): String = 
  try s catch { case t: Throwable => t.toString }

def foo: String = lazily("foo")
def bar: String = lazily(return "bar")

scala> foo
res5: String = foo

scala> bar
res6: String = scala.runtime.NonLocalReturnControl

To those who say well you should never catch Throwable anyway, I say well you shouldn’t be using exceptions for flow control. The breakable { ... } nonsense in stdlib uses a similar technique and similarly should not be used.

Another example. What if a return expression is captured and not evaluated until after the containing method has returned? Well you now have a time-bomb that will blow up whenever it’s evaluated.

scala> def foo: () => Int = () => return () => 1
foo: () => Int

scala> val x = foo
x: () => Int = <function0>

scala> x()
scala.runtime.NonLocalReturnControl

And as an extra bonus NonLocalReturnControl extends NoStackTrace so you are given no clue about where the bomb was manufactured. Good stuff.

For this reason, if you make a choice to use return, you should practice safe returns and use -Xlint:nonlocal-return, available with 2.13:

scala> def foo: () => Int = () => return () => 1
                                  ^
warning: return statement uses an exception to pass control 
to the caller of the enclosing named method foo

foo: () => Int

However, the safest practice remains abstinence.

What is the type of a return expression?

In return a the returned expression a must conform with the return type of the method in which it appears, but the expression return a itself also has a type, and from its “abandon the computation” semantics you can probably guess what that type is. If not, here’s a progression for you.

def x: Int = { val a: Int = return 2; 1 } // result is 2

Well this typechecks so our guess might be that the type of return a is the same as the type of a. So let’s test that theory by trying something that shouldn’t work.

def x: Int = { val a: String = return 2; 1 } 

Hmm, that typechecks too. What’s going on? Whatever the type of return 2 is, it conforms with both Int and String. And since both of those classes are final and Int is an AnyVal you know where this is headed.

def x: Int = { val a: Nothing = return 2; 1 } 

Right. So, whenever you encounter an expression of type Nothing you would do well to turn smartly and head the other direction. Because Nothing is uninhabited (there are no values of that type) you know that the expression has no normal form; when evaluated it must loop forever, exit the VM, or (behind door #3) abruptly pass control elsewhere, which is what’s happening here.

If your reaction is “well logically you’re just invoking the continuation, which we totally do all the time in Scheme so I don’t see the problem” then fine. Cookie for you. The rest of us think it’s insane.

Return is not referentially transparent.

This kind of goes without saying, but just in case you’re not sure what this means, if I say

def foo(n:Int): Int = {
  if (n < 100) n else return 100
}

then I should be able to rewrite my program thus, with no change in meaning

def foo(n: Int): Int = {
  val a = return 100
  if (n < 100) n else a
}

which of course doesn’t work. Evaluating a return expression is a side-effecting operation.

But what if I "really" need it?

You don’t. If you find yourself in a situation where you think you want to return early, you need to re-think the way you have defined your computation. For example:

// Add up the numbers in a list, up to 100 max
def max100(ns: List[Int]): Int = 
  ns.foldLeft(0) { (n, m) => 
    if (n + m > 100) 
      return 100 
    else 
      n + m
  }
can be rewritten using simple tail recursion:

// Add up the numbers in a list, up to 100 max
def max100(ns: List[Int]): Int = {
  def go(ns: List[Int], a: Int): Int = 
    if (a >= 100) 100
    else ns match {
      case n :: ns => go(ns, n + a)
      case Nil     => a
    }
  go(ns, 0)
}

This is always possible. Eliminating return from the Scala language would result in zero programs that could no longer be written. It may take a bit of effort to get into the mindset, but in the end you will find that writing computations that terminate properly is far easier than trying to reason about side-effects manifested as nonlocal flow control.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266