Groovy调用泛型方法无法编译

时间:2017-12-29 12:13:09

标签: generics groovy closures

我有Java 8 + Groovy 2.4.12,下面的代码编译并运行。

import java.util.function.Consumer
import groovy.transform.CompileStatic

@CompileStatic
class Bar {

    public static <T> void foo(T a, Consumer<T> c) { c.accept(a) }

    static void main(args) {
        ['a','b'].each {
            int xyz
            xyz = 1
            foo('') {
                println '1'
                return
            }
        }
    }
}

但如果您注释掉return,编译器会说

Groovy:[Static type checking] - Cannot call <T> Bar#foo(T, java.util.function.Consumer <T>) with arguments [java.lang.String, groovy.lang.Closure 

此外,如果你注释掉xyz值赋值,那么它就可以了。因此,下面的代码编译并运行:

['a','b'].each {
    int xyz
//  xyz = 1
    foo('') {
        println '1'
    //  return
    }
}

这似乎是一种特殊情况,只有在你有:

时才会发生
  • @CompileStatic注释
  • 具有两个参数的通用方法;第一个是通用类型和 第二个是相同泛型类型的接口
  • 调用那个泛型方法,第二个参数作为闭包,全部包含在另一个闭包中。
  • 调用前的变量声明和值赋值(如果在两个单独的行或单行上没有区别,如int xyz = 1

我的问题是;这是一个编译器错误还是有一个理性的原因,为什么它不编译没有return语句,但编译它?或者为什么添加变量定义会打破它?

1 个答案:

答案 0 :(得分:0)

  

我的问题是;这是一个编译器错误还是有理性的原因   为什么它没有返回语句就编译但是用它编译?

前者。

相关问题