【问题标题】:Groovy CompileStatic with generic lists带有通用列表的 Groovy CompileStatic
【发布时间】:2017-02-14 14:19:19
【问题描述】:

我在 groovy 中有以下代码:

class Test {
  List<Integer> yo(boolean x) {
    List<Integer> res = x ? [] : [1, 2, 3]
  }
}

在我将@CompileStatic 注释添加到类之前,它编译得很好。然后编译失败

Test.groovy: 5: [Static type checking] - Incompatible generic argument types. Cannot assign java.util.List <? extends java.lang.Object> to: java.util.List <Integer>
 @ line 5, column 27.
       List<Integer> res = x ? [] : [1, 2, 3]

是否真的期望 Groovy 无法推断该空列表 [] 的泛型类型?

【问题讨论】:

  • [] 有一个 iferred 类型 List&lt;Object&gt;,从我的 PoV 来看这很好。与null相同
  • 在这种特殊情况下,具有List&lt;Integer&gt; 类型的 LHS 我以某种方式期望[] 属于同一类型...因为List&lt;Integer&gt; l = [] 确实有效...
  • 这看起来像 Groovy 错误。

标签: generics groovy


【解决方案1】:

我建议你根本不要使用泛型。对我来说,它编译并运行良好,就像这样:

List res = x ? [] : [1, 2, 3]

但如果你仍然强烈需要泛型,试试这个:

List<Integer> res = x ? [] as List<Integer> : [1, 2, 3]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 2013-03-03
    • 2013-01-23
    • 1970-01-01
    相关资源
    最近更新 更多