Skip to content

Instantly share code, notes, and snippets.

@buryat
Created January 10, 2018 19:00
Show Gist options
  • Save buryat/8d4b9e6e56195629e377cf7cbd6599e9 to your computer and use it in GitHub Desktop.
Save buryat/8d4b9e6e56195629e377cf7cbd6599e9 to your computer and use it in GitHub Desktop.
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)
}
}
@buryat
Copy link
Author

buryat commented Jan 10, 2018

also notice how the compiled code isn't entirely what we want, because return bubbles up into t and not into the anonymous function of map, so the result might not be correct

@buryat
Copy link
Author

buryat commented Jan 10, 2018

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