Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Object.metaClass.doLoop = { proc ->
def temp = new Object() {
def e = new Exception() // 一時的な例外
def doBreak = { throw this.e } // doBreak() の形でeをthrowできるようにする
def doContinue = { throw this.e } // doContinue() の形でeをthrowできるようにする
}
proc.delegate = temp // proc内でtempを使えるようにする
[ // whileの実装
'while': { cond ->
try {
proc()
while(cond()) {
proc()
}
} catch(ex) { if (!ex.is(temp.e)) throw ex }
},
// untilの実装
'until': { cond ->
try {
proc()
} catch(ex) { if (!ex.is(temp.e)) throw ex }
while(!cond()) {
try {
proc()
} catch(ex) { if (!ex.is(temp.e)) throw ex }
}
}
]
}
// 以下、デモ
Object.metaClass.lnprint = { println(); print it }
def a = 1
print "[1.In do-while loop]".padRight(35)
doLoop {
print "[$a]"
a++
}.while{ a < 10 }
lnprint "[2.In do-while loop with break]".padRight(35)
doLoop {
print "[$a]"
if (a == 15) doBreak() // 15になったらbreak
a++
}.while{ a < 20 }
lnprint "[3.In do-until loop]".padRight(35)
doLoop {
print "[$a]"
a++
}.until{ a == 25 }
lnprint "[4.In do-until loop with continue]".padRight(35)
doLoop {
a++
if (a < 35) doContinue() // 35より小さい場合はcontimue
print "[$a]"
}.until{ a == 40 }
// こちらは以前試していた失敗作
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