Skip to content

Instantly share code, notes, and snippets.

@fumokmm
Created April 8, 2011 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fumokmm/909738 to your computer and use it in GitHub Desktop.
Save fumokmm/909738 to your computer and use it in GitHub Desktop.
Object.metaClass.doloop = { proc ->
[ // whileの実装
'while': { cond ->
proc()
while(cond()) {
proc()
}
},
// untilの実装
'until': { cond ->
proc()
while(!cond()) {
proc()
}
}
]
}
// 以下、デモ
def a = 1
doloop {
println "[in do-while loop] $a"
a++
}.while{ a < 10 }
doloop {
println "[in do-until loop] $a"
a++
}.until{ a == 20 }
// こちらは以前試していた失敗作
class DoWhile {
def proc
def _do(Closure proc) {
this.proc = proc
return this
}
def _while(Closure cond) {
10.times {
println cond()
this.proc()
}
}
}
def dw = new DoWhile()
int i = 0
dw._do {
println "hello ${++i}"
}._while {
i < 50
}
// => java.lang.VerifyError: (class: ConsoleScript46$_run_closure2, method: doCall signature: (Ljava/lang/Object;)Ljava/lang/Object;) Expecting to find integer on stack
// at ConsoleScript46.run(ConsoleScript46:17)
// at groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:266)
// at groovy.lang.GroovyShell.run(GroovyShell.java:517)
// at groovy.lang.GroovyShell.run(GroovyShell.java:172)
// at groovy.lang.GroovyShell$run.call(Unknown Source)
// at groovy.ui.Console$_runScriptImpl_closure16.doCall(Console.groovy:910)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment