简体   繁体   English

从Gradle中的Groovy闭包返回价值的更好方法

[英]Better way to return value from a Groovy closure in Gradle

The below code works. 下面的代码有效。 It gets a collection of all the different task groups in Gradle and prints them out. 它在Gradle中获取所有不同任务组的集合,并将它们打印出来。 I was hoping there was a better way to do this. 我希望有更好的方法来做到这一点。 Part of the problem is the only way I can access all tasks is via the all() method which has this signature void all(Closure var1); 问题的一部分是我可以访问所有任务的唯一方法是通过all()方法,该方法具有此签名void all(Closure var1); which is very frustrating because of just returning a collection, I get a closure that can iterate over the collection. 由于仅返回一个集合,这非常令人沮丧,我得到了一个可以迭代集合的闭包。

afterEvaluate { Project project ->
    def blah = []
    project.tasks.all { Object object ->
        blah << object.group
    }
    println blah.unique()
}

I was hoping there was a better way to do this than stashing values in a variable defined outside the closure. 我希望有比将值存储在闭包外部定义的变量中更好的方法。 The primary problem here is that as the closure runs I only have access to one group name at a time, and I want to unique them, and I can't return anything from the all function because the return type is void. 这里的主要问题是,在运行闭包时,我一次只能访问一个组名,并且我想对它们进行唯一性设置,并且由于返回类型为空,因此我无法从all函数返回任何内容。

As project.tasks is a collection, have you tried something like 由于project.tasks是一个集合,您是否尝试过类似

afterEvaluate { Project project ->
    println project.tasks.collect { it.group }.unique()
}

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

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