简体   繁体   English

Groovy:封闭中的冒号?

[英]Groovy: colon mark in closure?

I am trying to make my own Dsl and was playing around with different styles of closures in groovy.我正在尝试制作自己的 Dsl,并且在 groovy 中尝试了不同风格的闭包。 I've stumbled upon follwing snippet:我偶然发现了以下片段:

myClosure {
  testProperty: "hello!"
}

But can't figure out if this a valid code and how can I access then this testProperty .但无法确定这是否是有效代码以及我如何访问此testProperty Is it valid?它有效吗? How can I read "hello!"我怎么读"hello!" value?价值?

For now, lets put aside closures, consider the following code:现在,让我们抛开闭包,考虑以下代码:

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

This compiles (therefor the syntax is valid) and prints:这将编译(因此语法有效)并打印:

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

So what you see here is just a labeled statement (groovy supports labels see here )所以你在这里看到的只是一个带标签的语句(groovy 支持标签见这里

And bottom line the code of f1 (just like f2) is:底线 f1(就像 f2)的代码是:

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

With closures its just the same from this standpoint:从这个角度来看,闭包也是一样的:

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

method {
   test : "hello"
}

This prints这打印

hello
class java.lang.String

as expected正如预期的那样

Usually in DSL you have either this:通常在 DSL 中你有这样的:

mySomething {
  a = 42
  b = 84
}

which corresponds to property setting对应属性设置

or this:或这个:

mySomething( a:42, b:84 ){
   somethingElse{}
}

which is a method call with Map-literal.这是一个带有 Map-literal 的方法调用。

The code you shown is not used as @mark-bramnik explained.您显示的代码未按照@mark-bramnik 的说明使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM