Update Scala - clarify return keyword usage

Add an example to clarify that the `return` keyword only returns from the inner-most `def` that surrounds it not the output of the lambda function.
This commit is contained in:
Ali Panahi 2020-05-30 12:31:36 -04:00 committed by GitHub
parent 54c34420f8
commit f69c039f1c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -252,7 +252,7 @@ weirdSum(2, 4) // => 16
// The return keyword exists in Scala, but it only returns from the inner-most // The return keyword exists in Scala, but it only returns from the inner-most
// def that surrounds it. // def that surrounds it.
// WARNING: Using return in Scala is error-prone and should be avoided. // WARNING: Using return in Scala is error-prone and should be avoided.
// It has no effect on anonymous functions. For example: // It has no effect on anonymous functions. For example here you may expect foo(7) should return 17 but it returns 7:
def foo(x: Int): Int = { def foo(x: Int): Int = {
val anonFunc: Int => Int = { z => val anonFunc: Int => Int = { z =>
if (z > 5) if (z > 5)
@ -260,9 +260,10 @@ def foo(x: Int): Int = {
else else
z + 2 // This line is the return value of anonFunc z + 2 // This line is the return value of anonFunc
} }
anonFunc(x) // This line is the return value of foo anonFunc(x) + 10 // This line is the return value of foo
} }
foo(7) // => 7
///////////////////////////////////////////////// /////////////////////////////////////////////////
// 3. Flow Control // 3. Flow Control