[英]How to give groovy closure parameter a type
I know closures have implicit type 'it' such that we can define a function我知道闭包有隐式类型 'it' 这样我们就可以定义一个函数
def int foo(int num, Closure closure){
def sum = num
sum+=closure.call(1)
}
then i call this function like然后我把这个函数称为
def total = foo(1,{it+1})
print total
//prints 2
My question is how do i force the closure to take an explicit parameter of type int.我的问题是如何强制闭包采用 int 类型的显式参数。 Like how we can define lambda functions in java.
就像我们如何在 Java 中定义 lambda 函数一样。
You can use @ClosureParam
to annotate your Closure
argument declaration with its parameters specifications.您可以使用
@ClosureParam
用其参数规范来注释您的Closure
参数声明。 In your particular case:在您的特定情况下:
import groovy.transform.stc.ClosureParams
import groovy.transform.stc.FirstParam
int foo(int num, @ClosureParams(FirstParam) Closure closure) {
def sum = num
sum += closure.call(5)
}
where FirstParam
is a hint that says that the argument of closure
is of type equals as the first parameter of this method.其中
FirstParam
是一个提示,表示closure
的参数类型等于此方法的第一个参数。
Complete code on GitHub GitHub 上的完整代码
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.