What will be printed out as the result of the following code execution?

object Main extends App {
  def f(): Int = try { return 1 } finally { return 2 }
  def g(): Int = try { 5 } finally { 7 }
  
  println(f() + g())
}
Explanation
If you're familiar with Java, 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.
That's why f() will return 2 and g() will return 5, as there is no return statement in finally block of g() function.
Source: Exception handling with try expressions

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback