Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of finally block in Scala [duplicate]

Tags:

scala

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

There are two Scala functions:

a): def foo(): Int = try { 1 } finally { 2 }

b): def bar(): Int = try { return 1 } finally { return 2}

I cannot figure out why foo returns 1 but bar returns 2.

like image 706
卢声远 Shengyuan Lu Avatar asked Dec 16 '22 16:12

卢声远 Shengyuan Lu


2 Answers

This behavior is explained in "Programming in Scala" by M.Odersky, L. Spoon and B.Venners. I have the first edition and section 7.5 (pg. 128) says:

it’s worth noting that Scala’s behavior differs from Java only because Java’s try-finally does not result in a value. As in Java, if a finally clause includes an explicit return statement, or throws an exception, that return value or exception will “overrule” any previous one that originated in the try block or one of its catch clauses. For example, given:

def f(): Int = try { return 1 } finally { return 2 }

calling f() results in 2. By contrast, given:

def g(): Int = try { 1 } finally { 2 }

calling g() results in 1. Both of these functions exhibit behavior that could surprise most programmers, thus it's usually best to avoid returning values from finally clauses.


Scala standard library has scala.util.control.Exception API that provides small functional library for handling exceptions. See the examples in scaladoc

like image 165
Alexander Azarov Avatar answered Jan 07 '23 16:01

Alexander Azarov


The return statement of the finally block of bar() exits the method bar(). Therefor the result of the try block is not returned.

This example shows a (roughly) equivalent version of your methods foo() and bar():

object Test extends App {

    def foo() = {
      val result = { 1 }
      { 2 }
      result
    }

    def bar(): Int = {
      val result = { 1 }
      { return 2 }
      result // this line is not processed
    }

    println("foo = " + foo()) // foo = 1

    println("bar = " + bar()) // bar = 2

}
like image 37
Daniel Dietrich Avatar answered Jan 07 '23 17:01

Daniel Dietrich