简体   繁体   English

Groovy DSL:如何隐藏闭包参数?

[英]Groovy DSL: How to hide closure parameter?

I am trying to implement a mini DSL with Groovy: 我正在尝试使用Groovy实现一个迷你DSL:

def parent(closure){
    def container = new ArrayList<>()
    closure.call(container)
    container
}

def child(element, parent) {
    println "add child$element to parent"
    parent.add(element)
}

parent{ it->
    child(1, it)
    child(2, it)
}

But I want to remove the it parameter to make it looks better, like this: 但是我想删除it参数以使其看起来更好,如下所示:

parent{ 
    child(1)
    child(2)
}

Is it possible to do it this way? 有可能这样做吗? Many thanks in advance. 提前谢谢了。

It's not a full solution, only example, but I think, you should do it this way: 这不是一个完整的解决方案,只是一个例子,但我想,你应该这样做:

class Parent{
    def container = new ArrayList<>()
    def child(element) {
        println "add child$element to parent"
        container.add(element)
    }

    def parent(Closure closure){
        closure.delegate = this
        closure.resolveStrategy = Closure.DELEGATE_FIRST
        closure.call()
        container
    }
}


new Parent().parent {
    child(1) // Here we are trying to resolve child method in our delegate, then owner.
    child(2)
}

Of course, you can remove new Parent in future, it's only quick example, to show you delegate magic. 当然,你可以在将来删除新的Parent,这只是一个快速的例子,向你展示委托魔法。

You can use @Field AST in the script if you do not want to create a whole separate class for it: 如果您不想为它创建一个完整的单独类,可以在脚本中使用@Field AST:

import groovy.transform.Field

@Field ArrayList container = new ArrayList<>()

//or just list
//@Field def container = []

def parent(Closure closure){
    closure.call()
    container
}

def child(element) {
    println "add child$element to parent"
    container << element
}

parent {
    child(1)
    child(2)
}

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

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