Skip to content

Instantly share code, notes, and snippets.

@nobeans
Last active December 12, 2015 04:42
Show Gist options
  • Save nobeans/80b3cee12cb9851baf58 to your computer and use it in GitHub Desktop.
Save nobeans/80b3cee12cb9851baf58 to your computer and use it in GitHub Desktop.
switchはbreakとかfall-throughとか気にしたくないしreturnで使いたいが、別メソッドに分けるほどでもないときに、クロージャを使うといいかもしれない、というサンプル
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