List <t>返回异常,接受varargs List <! - ?延伸T - >

时间:2016-08-24 07:25:57

标签: java generics groovy variadic-functions

在下面的代码中,我期望返回类型为List<A>类型,但结果是List<Ax>类型(第一个varargs参数的类型)。如果有人能够理解为什么会这样,请向我解释。另请注意,特定类型的返回列表实际上包含兄弟类型的元素。

import groovy.transform.CompileStatic

@CompileStatic
class Main {
    static main(args) {
      List<Ax> axl = [new Ax()]
      List<Ay> ayl = [new Ay()]
      List<Az> azl = [new Az()]

      // List<A> list1 = Util.join(axl, ayl, azl)
      // Error: Incompatible generic argument types. Cannot assign java.util.List <Ax>
      //        to: java.util.List <A>

      List<A> list2 = Util.join(axl, ayl, azl) as List<A>  // coercion works
      list2.each { A a -> println a.getClass() } // 3 different types     

      List<Ax> list3 = Util.join(axl, ayl, azl) // List<Ax> holds Ay and Az!!! Type system flawed
      // list3.each { Ax a -> println a.getClass() } // some weird error
      list3.each { A a -> println a.getClass() } // 3 different types
    }
}

@CompileStatic class A {}
@CompileStatic class Ax extends A {}
@CompileStatic class Ay extends A {}
@CompileStatic class Az extends A {}

@CompileStatic
class Util {
    static <T> List<T> join(List<? extends T>... lists) {
        List<T> joined = [] 
        lists.each { List<? extends T> list ->
          list.each { T elm -> joined.add(elm) }
        }
        return joined
    }
}

注意:Groovy版本:2.4.7

0 个答案:

没有答案