Created
January 10, 2018 19:00
-
-
Save buryat/8d4b9e6e56195629e377cf7cbd6599e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object TestReturn { | |
def t(n: Int): Boolean = { | |
(1 to n).map(x => { | |
if (x > 5) return true | |
false | |
}).exists(_ == true) | |
} | |
} | |
object TestReturn2 { | |
def t(n: Int): Boolean = { | |
(1 to n).map(x => | |
if (x > 5) { | |
true | |
} else { | |
false | |
} | |
).exists(_ == true) | |
} | |
} |
Here's an example of when it works not the way we expected
object TestReturn {
def t(n: Int): Boolean = {
(1 to n).map(x => {
if (x == 5) return false
true
}).last
}
}
object TestReturn2 {
def t(n: Int): Boolean = {
(1 to n).map(x =>
if (x == 5) {
false
} else {
true
}
).last
}
}
scala> object TestReturn {
| def t(n: Int): Boolean = {
| (1 to n).map(x => {
| if (x == 5) return false
| true
| }).last
| }
| }
defined object TestReturn
scala> TestReturn.t(10)
res0: Boolean = false
But it should've returned true
since we're past 5
scala> object TestReturn2 {
| def t(n: Int): Boolean = {
| (1 to n).map(x =>
| if (x == 5) {
| false
| } else {
| true
| }
| ).last
| }
| }
defined object TestReturn2
scala> TestReturn2.t(10)
res1: Boolean = true
And this returns correct result, since it actually goes all the way to the last element
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
also notice how the compiled code isn't entirely what we want, because
return
bubbles up intot
and not into the anonymous function ofmap
, so the result might not be correct