gpt4 book ai didi

Groovy:关闭中的冒号标记?

转载 作者:行者123 更新时间:2023-12-04 02:39:51 25 4
gpt4 key购买 nike

我正在尝试制作自己的 Dsl,并在 groovy 中尝试使用不同风格的闭包。我偶然发现了以下片段:

myClosure {
testProperty: "hello!"
}

但无法弄清楚这是否是有效代码以及我如何才能访问此 testProperty。有效吗?如何读取 "hello!" 值?

最佳答案

现在,让我们抛开闭包,考虑以下代码:

def f1() {
testProperty : 5
}
def f2() {
testProperty : "Hello"
}
println f1()
println f1().getClass()
println f2()
println f2().getClass()

这会编译(因此语法有效)并打印:

5
class java.lang.Integer
Hello
class java.lang.String

所以你在这里看到的是只是一个带标签的语句(groovy 支持标签 see here )

最重要的是,f1 的代码(就像 f2 一样)是:

def f1() {
return 5 // and return is optional, so we don't have to write it
}

从这个角度来看,闭包是一样的:

​def method(Closure c) {
def result = c.call()
println result
println result.getClass()
}

method {
test : "hello"
}

这打印

hello
class java.lang.String

如预期的那样

关于Groovy:关闭中的冒号标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59859951/

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