I know closures have implicit type 'it' such that we can define a function
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. Like how we can define lambda functions in java.
You can use @ClosureParam
to annotate your Closure
argument declaration with its parameters specifications. 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.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.