5

Here's the code in Scala cli:

scala> def ff(): Int = try {return 1} finally {return 2}

scala> println(ff())
2

scala> def gg(): Int = try {1} finally {2}

scala> println(gg())
1

I want to know why there's distinction whether or not adding the return keyword? Thanks a lot!

Judking
  • 6,111
  • 11
  • 55
  • 84

1 Answers1

2

The return statement within finally conceptually will override the original return in try block. But if you do not use return, Scala picks the last expression of try block as the result of the computation and finally is just executed as side effect and does not have any effect on the result of function. You may take a look at this thread as well.

Community
  • 1
  • 1
Nami
  • 1,215
  • 11
  • 21