gpt4 book ai didi

groovy - 向 Groovy DSL 添加可选子句

转载 作者:行者123 更新时间:2023-12-02 03:27:31 24 4
gpt4 key购买 nike

我正在使用 Groovy 开发 DSL,但遇到了以下问题。我有一个方法可以对具有给定参数的对象执行一些操作。

def run(x) {
[with:{ y -> foo(x,y) }]
}

run "thing" with "param" // evaluates to foo("thing","param")

现在,假设我想向我的 DSL 添加一个默认功能:

def runDefault(x) {
foo(x)
}

runDefault "thing" // evaluates to foo("thing")

有没有办法将两者组合成一个函数,使 with "param" 部分成为可选子句?我希望能够使用如下所示的 DSL:

run "thing" with "param"    // should do foo("thing","param")
run "thing" // should do foo("thing")

最佳答案

如果您能够区分运行方法中的两个调用,您可以这样做:

def run(x) {
switch (x) {
case 'foo':
println "foo($x)"; break;
case 'bar':
[with:{ y -> println "bar($x,$y)" }]; break;
}
}
run "bar" with "param"
run "foo"

关于groovy - 向 Groovy DSL 添加可选子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29660737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com