I am learning Scala and I noticed something about using the return statement.
So, obviously, in Scala, if you don't have a return statement, the last value is returned by default. It's great. But if you use the return statement without specifying the return type, Scala says "error: method testMethod has return statement; needs result type"
So it works
def testMethod(arg: Int) = { arg*2 }
but it gives an error
def testMethod(arg: Int) = { return arg*2 }
It makes me scratch my chin and go
Mmmmmmmm ... There must be a reason for this.
Why is an explicit type declaration required when you use the return statement, but not when Scala returns the last value? I assumed that they were exactly the same and that the return statements are only for you to return a value inside a nested function / conditional, etc. (In other words, the "return" statement is automatically added to your last value by the compiler .. if not present anywhere in the method)
But obviously, I was wrong. Surely there must be some other difference in implementation?
Did I miss something?
source share