groovy - 如何在 Groovy 中定义 @CompileStatic 兼容闭包?

标签 groovy closures groovy++

我有一个类,其闭包定义为:

void everyPixel( closure ){
    for( def x : 0..width-1 )
        for( def y : 0..height-1 )
            closure( x, y )
}

但是,如果我对其应用 @CompileStatic 注释,它就不会编译(它在我添加闭包之前编译),并显示以下消息:

Groovyc: [Static type checking] - Cannot find matching method java.lang.Object#call(java.lang.Integer, java.lang.Integer). Please check if the declared type is right and if the method exists.

如何为此创建类型签名以便静态编译?到目前为止,我在 Google 上的所有点击都是说如何传递闭包,而不是如何定义接受闭包的方法。 :-/

最佳答案

你只需要告诉它closure是一个Closure:

void everyPixel( Closure closure ){
  for( x in 0..<width )
    for( y in 0..<height )
      closure( x, y )
}

关于groovy - 如何在 Groovy 中定义 @CompileStatic 兼容闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15423714/

相关文章:

javascript - 创建具有值参数而不是引用的函数引用

Swift - 代码不返回外部闭包的数组值

grails - 在 Grails 中使用 Groovy++ 的经验

groovy - Groovy 中带类型参数的闭包

java - 使用静态编译的 Groovy 2.0 的性能如何

spring-boot - org.dozer.MappingException:找不到类中字段(metaClass)的读取或写入方法

gradle - 无法加载类 grails.plugins.rendering.image.ImageRenderingService Grails 4 渲染 :2. 03

grails - 无法在Grails/Groovy Web应用程序中执行Update()

unit-testing - 在 groovy 和 spock 中为不同的类运行相同的测试

python - 装饰器中不同类型的变量是否有不同的作用域? (Python)