“return” and “try-catch-finally” block evaluation in scala

前端 未结 2 1095
春和景丽
春和景丽 2020-12-03 11:23

The following two code generate different result:

def x = try{
  true
} finally false

invoke x gets true

def y         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 11:33

    According to the Scala language spec:

    A try expression try { b } finally e evaluates the block b. If evaluation of b does not cause an exception to be thrown, the expression e is evaluated. If an exception is thrown during evaluation of e, the evaluation of the try expression is aborted with the thrown exception. If no exception is thrown during evaluation of e, the result of b is returned as the result of the try expression.

    This behaviour would seem to be in contradiction with that spec. I would guess that, since 'return' causes an immediate return from the function, this results in overriding the standard behaviour for a try block. An illuminating example is:

    def z : Boolean = {
      val foo = try { true } finally { return false }
      true
    }
    

    Invoking z returns false.

提交回复
热议问题