Groovy staic打字的这个漏洞有机会得到修复

当我运行以下Groovy代码片段时,按预期显示“,a,b,c”:

@CompileStatic public static void main(String[] args) { def inList = ["a", "b", "c"] def outList = inList.inject("", { a, b -> a + "," + b }) println(outList) } 

现在我将第一个参数从一个空字符串中注入到数字0:

 @CompileStatic public static void main(String[] args) { def inList = ["a", "b", "c"] def outList = inList.inject(0, { a, b -> a + "," + b }) println(outList) } 

这将无法正常工作产生一个异常“不能强制类'java.lang.String'类'java.lang.Number'”。 问题是编译器没有抱怨。 我在Scala和Kotlin(注入被称为折叠)中尝试了这一点,各自的编译器抱怨不符合预期。 此外,在Java8的对手不编译(它说,发现int,必需:java.lang.String):

 List<String> list = Arrays.asList("a", "b", "c"); Object obj = list.stream().reduce(0, (x, y) -> x + y); System.out.println(obj); 

现在的问题是,这是否可以在Groovy中修复,或者这是一个普遍的问题,因为静态类型被引入到语言中。

我认为(我不是100%确定的),这是Groovy中的一个bug,很可能是类型推断的某个地方,它可以被修复。 尝试在错误跟踪器中填写问题 。

如果你想看到编译错误,你可以给类型封闭参数

 inList.inject(0, { String a, String b -> a + "," + b }) 

给出一个错误:

 Expected parameter of type java.lang.Integer but got java.lang.String @ line 7, column 38. def outList = inList.inject(0, { String a, String b -> a + "," + b}) ^ 
Interesting Posts