2017-02-14 25 views
1

我在常規下面的代碼:Groovy的CompileStatic與泛型列表

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不能推斷泛型類型的空單[]的?

+0

'[]'有iferred類型'名單'這是罰款從我的PoV。與'null'相同 – injecteer

+0

在這種特殊情況下,有一個'List '類型的LHS,我以某種方式預計'[]'是同一類型的...因爲'列表 l = []'確實有效...... – Nikem

+0

這看起來像Groovy的bug。 – Dany

回答

0

我建議你不要使用泛型。對於我來說,編譯和運行良好的就像這樣:

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

但是,如果你仍然強烈需要仿製藥試試這個:

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