Last active
December 12, 2015 04:42
-
-
Save nobeans/80b3cee12cb9851baf58 to your computer and use it in GitHub Desktop.
switchはbreakとかfall-throughとか気にしたくないしreturnで使いたいが、別メソッドに分けるほどでもないときに、クロージャを使うといいかもしれない、というサンプル
This file contains hidden or 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
import static groovy.test.GroovyAssert.* | |
def hoge(x) { | |
switch (x) { | |
case 1: return "A" | |
case 2: return "B" | |
default: throw new Exception("HOGE") | |
} | |
} | |
def foo(x) { | |
def r = {-> | |
switch (x) { | |
case 1: return "A" | |
case 2: return "B" | |
default: throw new Exception("HOGE") | |
} | |
}() | |
return r + "!" | |
} | |
assert hoge(1) == "A" | |
assert hoge(2) == "B" | |
shouldFail(Exception) { | |
hoge(9) | |
} | |
assert foo(1) == "A!" | |
assert foo(2) == "B!" | |
shouldFail(Exception) { | |
foo(9) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment