我在 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 无法推断该空列表 []
的泛型类型?
最佳答案
我建议您根本不要使用泛型。对我来说,它可以像这样编译和运行:
List res = x ? [] : [1, 2, 3]
但是如果你仍然强烈需要泛型,试试这个:
List<Integer> res = x ? [] as List<Integer> : [1, 2, 3]
关于generics - 带有通用列表的 Groovy CompileStatic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42228516/