Groovy:闭包中的冒号标记?
我正在尝试制作自己的Dsl,并在groovy中使用了不同风格的闭包。 我偶然发现了以下片段:Groovy:闭包中的冒号标记?,groovy,Groovy,我正在尝试制作自己的Dsl,并在groovy中使用了不同风格的闭包。 我偶然发现了以下片段: myClosure { testProperty: "hello!" } 但无法确定这是否是有效代码,以及如何访问该testProperty。它有效吗?如何读取“hello”?值> ,让我们搁置闭包,考虑下面的代码: def f1() { testProperty : 5 } def f2() { testProperty : "Hello" } println f1() print
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支持标签)
f1(和f2一样)的代码是:
从这个角度来看,闭包也是一样的:
def method(Closure c) {
def result = c.call()
println result
println result.getClass()
}
method {
test : "hello"
}
这张照片
hello
class java.lang.String
正如预期的那样通常在DSL中,您有以下两种情况之一:
mySomething {
a = 42
b = 84
}
它对应于属性设置
或者这个:
mySomething( a:42, b:84 ){
somethingElse{}
}
这是一个使用Map literal的方法调用
您显示的代码没有按照@mark bramnik解释的那样使用。哦,非常感谢!在文档中找不到它
mySomething( a:42, b:84 ){
somethingElse{}
}