Skip to content

Instantly share code, notes, and snippets.

@int128
Last active August 29, 2015 14:14
Show Gist options
  • Save int128/6fee4e6179553b14d02b to your computer and use it in GitHub Desktop.
Save int128/6fee4e6179553b14d02b to your computer and use it in GitHub Desktop.
Groovy trait
trait T {
private a(x) { "--$x--" }
def b(x) { a(x) }
def c(xs) { xs.collect { x -> a(x) } }
}
class C {
}
def c = new C()
def m = c.withTraits T
m.b('hoge')
//m.c(['hoge'])
class E {
def e(x) { println "--- $x ---" }
}
trait T {
def b(x) {
withE(recursive.curry(x))
}
static recursive = { given ->
e(given)
if (given > 0) { call(given - 1) }
}
}
class C {
def withE(closure) { Utility.callWithDelegate(closure, new E()) }
}
def c = new C().withTraits T
c.b(10)
class Utility {
static <T> T callWithDelegate(Closure<T> closure, Object delegate) {
def cloned = closure.clone() as Closure<T>
cloned.resolveStrategy = Closure.DELEGATE_FIRST
cloned.delegate = delegate
cloned.call()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment