Created
December 29, 2010 23:54
-
-
Save jpertino/759243 to your computer and use it in GitHub Desktop.
groovy method dispatching with a little help
This file contains 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 Magic { | |
def methodMissing(String methodName, Object arguments) { | |
method(methodName, *arguments) | |
} | |
private method(String methodName, Object... arguments) { | |
if (!(arguments[-1] instanceof Closure)) | |
throw new MissingMethodException(methodName, this.class, arguments) | |
method(methodName, arguments[-1], *arguments[0..-2]) | |
} | |
private method(String methodName, Map map, Object... arguments) { | |
if (!(arguments[-1] instanceof Closure)) | |
throw new MissingMethodException(methodName, this.class, arguments) | |
method(methodName, map, arguments[-1], *arguments[0..-2]) | |
} | |
private method(String methodName, String... strings) { | |
println "$methodName(String... $strings)" | |
} | |
private method(String methodName, Map map) { | |
println "$methodName(Map $map)" | |
} | |
private method(String methodName, Closure closure) { | |
println "$methodName(Closure ${closure()})" | |
} | |
private method(String methodName, Map map, String... strings) { | |
println "$methodName(Map $map, String... $strings)" | |
} | |
private method(String methodName, Closure closure, String... strings) { | |
println "$methodName(Closure ${closure()}, String... $strings)" | |
} | |
private method(String methodName, Map map, Closure closure) { | |
println "$methodName(Map $map, Closure ${closure()})" | |
} | |
private method(String methodName, Map map, Closure closure, String... strings) { | |
println "$methodName(Map $map, Closure ${closure()}, String... $strings)" | |
} | |
} | |
new Magic().with { | |
s "string1", "string2" | |
// s(String... [string1, string2]) | |
m key1: "value1", key2: "value2" | |
// m(Map [key1:value1, key2:value2]) | |
c {"closure"} | |
// c(Closure closure) | |
sm "string1", key1: "value1", "string2", key2: "value2" | |
// sm(Map [key1:value1, key2:value2], String... [string1, string2]) | |
sc "string1", "string2", {"closure"} | |
// sc(Closure closure, String... [string1, string2]) | |
mc key1: "value1", key2: "value2", {"closure"} | |
// mc(Map [key1:value1, key2:value2], Closure closure) | |
smc "string1", key1: "value1", "string2", key2: "value2", {"closure"} | |
// smc(Map [key1:value1, key2:value2], Closure closure, String... [string1, string2]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment