Created
September 4, 2013 10:32
-
-
Save akhikhl/6435317 to your computer and use it in GitHub Desktop.
switch statement and closure comprehension
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
def isGreaterThan(a, b) { a > b } | |
def isGreaterThan(b) { | |
return { a -> isGreaterThan(a, b) } | |
} | |
def isLessThan(a, b) { a < b } | |
def isLessThan(b) { | |
return { a -> isLessThan(a, b) } | |
} | |
def x = 5 | |
def y = 6 | |
switch(x) { | |
case isGreaterThan(y): | |
println "$x is greater than $y" | |
break | |
case isLessThan(y): | |
println "$x is less than $y" | |
break | |
default: | |
println "$x equals $y" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The trick here is that single-argument versions of IsGreaterThan, IsLessThan return closures. Switch-statement “understands” closures: it passes it’s argument (x in our case) as a parameter to the closure and expects boolean result being returned from the closure.Same thing can be done via function currying, but it looks not so nice, as with function overload.