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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With