2011-08-27 58 views
15

我就這麼多,而願意寫這樣的:編譯錯誤: 「 '<>' 不能用匿名類可以用」

Lists.transform(vals, 
    new Function<>() { 
     public List<ValEntry> apply(Validator<? super T> input) { 
      return input.validate(value); 
     } 
    }); 

...比這

Lists.transform(vals, 
    new Function<Validator<? super T>, List<ValEntry>>() { 
     public List<ValEntry> apply(Validator<? super T> input) { 
      return input.validate(value); 
     } 
    }); 

但Java編譯器給我以下錯誤信息:

'<>' cannot be used with anonymous classes 

是否有這樣的根本原因?或者只是跳過JDK 7中的功能,也許他們在8?

+1

不要使用Java,Scala的更好的舞蹈...... – Landei

+3

打有時候在生活中,你別無選擇,只能打。 – Lii

+1

我不記得Java被設計成功能性語言 – Woot4Moo

回答

14

按照project coin documentation

Internally, a Java compiler operates over a richer set of types than those that can be written down explicitly in a Java program. The compiler-internal types which cannot be written in a Java program are called non-denotable types. Non-denotable types can occur as the result of the inference used by diamond. Therefore, using diamond with anonymous inner classes is not supported since doing so in general would require extensions to the class file signature attribute to represent non-denotable types, a de facto JVM change. It is feasible that future platform versions could allow use of diamond when creating an anonymous inner class as long as the inferred type was denotable.

編輯 所以有可能在未來的版本。 Java 8仍然無法實現,但現在我們有了lambda表達式,因此需求減少了。

+1

感謝您的研究。泛型和類型推斷的內部是有趣但複雜的事情。 – Lii

+4

我還是不明白。爲什麼將一個類體添加到構造函數調用中會禁止鑽石算子推斷類型參數? 'ArrayList a = new ArrayList <>();'是合法的,但'ArrayList a = new ArrayList <>(){};'不是。類型參數很明顯是'String'。爲什麼匿名類型的類文件不能這樣說? – thejoshwolfe

+0

仍然不可能用java 8 – gontard

3

現在這計劃將包含在Java中9.從JEP 213: Milling Project Coin

  1. Allow diamond with anonymous classes if the argument type of the inferred type is denotable . Because the inferred type using diamond with an anonymous class constructor could be outside of the set of types supported by the signature attribute, using diamond with anonymous classes was disallowed in Java SE 7. As noted in the JSR 334 proposed final draft, it would be possible to ease this restriction if the inferred type was denotable.