Last active
August 29, 2015 14:14
-
-
Save int128/6fee4e6179553b14d02b to your computer and use it in GitHub Desktop.
Groovy trait
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
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']) | |
|
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
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