gpt4 book ai didi

generics - Generic 类型的关闭参数 - 异常

转载 作者:行者123 更新时间:2023-12-04 12:57:34 35 4
gpt4 key购买 nike

在下面的代码中,为什么 Groovy 似乎忽略了方法 barMany 中提供的闭包参数的泛型类型声明:

import groovy.transform.CompileStatic

@CompileStatic
class Main {
static main(args) {
FooSub foo = new FooSub()
BarSub bar = new BarSub()
}
}

@CompileStatic
class Foo<T> {
void fooOne (T item) {}
void fooMany(List<T> items) {
items.each { T item -> fooOne(item) } // Compiles fine.
}
}

@CompileStatic
class FooSub extends Foo<Integer> {}

@CompileStatic
class Bar<T extends Bar<T>> {
void barOne (T item) {}
void barMany(List<T> items) {

items.each { T item -> barOne(item) } // Error:
// Cannot find matching method Bar#barOne(java.lang.Object) !!!

items.each { T item -> barOne(item as T) } // Error:
// Expected parameter of type java.lang.Object but got T !!!

items.each { item -> barOne(item as T) } // Compiles fine - closure knows about T

}
void barManyMore(List<T> items) {
for (T item in items) { // Compiles fine.
barOne(item) }
}
}

@CompileStatic
class BarSub extends Bar<BarSub> {}

更新 :
Groovy 版本:2.4.5 JVM:1.7.0_80 供应商:Oracle Corporation 操作系统:Linux

更新
所以有一个我以前没有注意到的奇怪错误 - org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed - 我将发布完整的输出:
~/grov/tests$ groovyc generics.groovy 
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
generics.groovy: 27: Expected parameter of type java.lang.Object but got T
@ line 27, column 19.
items.each { T item -> barOne(item) } // Error:
^

generics.groovy: 27: [Static type checking] - Cannot find matching method Bar#barOne(java.lang.Object). Please check if the declared type is right and if the method exists.
@ line 27, column 29.
items.each { T item -> barOne(item) } // Error:
^

generics.groovy: 30: Expected parameter of type java.lang.Object but got T
@ line 30, column 22.
items.each { T item -> barOne(item as T) } // Error:
^

3 errors

~/grov/tests$ groovyc -v
Groovy compiler version 2.4.5
Copyright 2003-2015 The Apache Software Foundation. http://groovy-lang.org/

更新

为了完整性,还有一些解决方法:
这些解决方法似乎有效:
    Closure c = { T item -> barOne(item) }; items.each c // See comments by @tim_yates
items.each ( { T item -> barOne(item) } as Closure) // Casting to closure works too!

当类型属于基于泛型 T 的类时,同样的问题也适用:
@CompileStatic
class Baz<T extends Baz<T>> {
List<T> getList() {
return [new T(), new T()]
}
}

@CompileStatic
class BazClient {
void useBaz(Baz baz) {
// baz.getList().each {Baz it -> println it} // Error
Closure c = {Baz it -> println it}; baz.getList().each c // works
baz.getList().each ({Baz it -> println it} as Closure) // works
}
}

最佳答案

这是一个与泛型相关的 bugs已在 Groovy 2.4.6 中修复。

关于generics - Generic 类型的关闭参数 - 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35145150/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com