In the following code, why Groovy seems to ignore the provided declaration of the universal closing parameter type in the barMany method:
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) }
Update : Groovy Version: 2.4.5 JVM: 1.7.0_80 Supplier: Oracle Corporation OS: Linux
Update So, there was this strange error that I had not noticed before - org.codehaus.groovy.control.MultipleCompilationErrorsException: the launch failed, I will print the full output:
~/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
Update
A few additional solutions for completeness: These workarounds seem to work:
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!
The same problem also applies when a type has a class based on a common T:
@CompileStatic class Baz<T extends Baz<T>> { List<T> getList() { return [new T(), new T()] } } @CompileStatic class BazClient { void useBaz(Baz baz) {
closures generics groovy
Basel shishani
source share