Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between writing 'return' explicitly and that implicitly in Scala? [duplicate]

Tags:

scala

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!

like image 968
Judking Avatar asked Nov 01 '22 09:11

Judking


1 Answers

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.

like image 168
Nami Avatar answered Nov 15 '22 07:11

Nami