From bcb1b623b1db1057085982507399c62eaa053e7b Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Fri, 23 Jun 2017 13:35:19 -0700 Subject: [scala/en] Make return value example actually demonstrate issue Previously the `return z` didn't actually have any effect on the output, since the outer function just return the anon function's result directly. Updated to make the outer function do something to demonstrate the difference. Also renamed functions to make what they're doing easier to follow, and added a couple examples of behavior w/ explanations --- scala.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 5eb94986..e541f4b3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -253,16 +253,20 @@ weirdSum(2, 4) // => 16 // def that surrounds it. // WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: -def foo(x: Int): Int = { - val anonFunc: Int => Int = { z => +def addTenButMaybeTwelve(x: Int): Int = { + val anonMaybeAddTwo: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of foo! + return z // This line makes z the return value of addTenButMaybeTwelve! else z + 2 // This line is the return value of anonFunc } - anonFunc(x) // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of foo } +addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 +addTenButMaybeTwelve(7) // Returns 7: 7 > 5, return value set to z, so + // last line doesn't get called and 10 is not added + ///////////////////////////////////////////////// // 3. Flow Control -- cgit v1.2.3