def ff(): Int = try {r...">

What is the difference between spelling "return" explicitly and implicitly in Scala?

Here is 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 is a difference in whether the return keyword is added or not? Many thanks!

+5
source share
1 answer

The return in finally conceptually redefines the original return block in try . But if you do not use return, Scala selects the last expression of the try block as a result of the calculation and, finally, just executes as a side effect and has no effect on the result of the function. You can watch this thread .

+2
source

Source: https://habr.com/ru/post/1213526/


All Articles