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

@viktorpodzigun Awesome! Happy to hear that :)

2020 Feb 17, 11:05:45 PM

Nice, learned something new today!

2020 Feb 15, 5:21:53 PM

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Scala
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести