java diamond 有什么用_Diamond语法何时在Java 8中不起作用?
從Java 7開始,菱形語法并不總是在方法參數(shù)中起作用,例如 為什么Diamond運(yùn)算符不適用于Java 7中的java.util.Collections方法? 。 該問題的答案提到Java 8中的目標(biāo)類型推斷可解決該問題。
是否還有其他情況無法使用菱形語法?
不是專門針對(duì)菱形運(yùn)算符,而是針對(duì)lambda返回類型的Java 8s類型推斷的弱點(diǎn):stackoverflow.com/q/26379408/502399
diamond運(yùn)算符不能總是在Java 8中使用。最初的改善Java 8推理的計(jì)劃(JEP 101)有兩個(gè)目標(biāo):
在方法上下文中添加對(duì)方法類型參數(shù)推斷的支持
添加對(duì)鏈?zhǔn)秸{(diào)用中方法類型參數(shù)推斷的支持
僅第一個(gè)實(shí)施。從JEP借用該示例,請(qǐng)考慮以下類:
class List {
static List cons(Z head, List tail) { ... };
E head() { ... }
}
在Java 8中,改進(jìn)的方法上下文推論允許以下內(nèi)容進(jìn)行編譯。使用Java 7,它將失敗并顯示錯(cuò)誤expected List, found List
List l = List.cons(42, new List<>());
但是,需要推理鏈?zhǔn)秸{(diào)用的示例仍不適用于Java 8:
Integer i = new List<>().head();
JSR 335的D部分包含有關(guān)為何Java 8放棄了鏈?zhǔn)奖磉_(dá)式推理的提示:
There has been some interest in allowing inference to"chain": in a().b(), passing type information from the invocation of b to the invocation of a. This adds another dimension to the complexity of the inference algorithm, as partial information has to pass in both directions; it only works when the erasure of the return type of a() is fixed for all instantiations (e.g. List). This feature would not fit very well into the poly expression model, since the target type cannot be easily derived; but perhaps with additional enhancements it could be added in the future.
還有一些其他無法使用鉆石的示例。
如果算錯(cuò)了,那么jdk8u25之前的javac不會(huì)編譯它。 (請(qǐng)參閱JDK-8029002)
class Test {
class C> {}
void m() {
C< ? > i = new C<>();
}
}
error: incompatible types: cannot infer type arguments for Test.C<>
C< ? > i = new C<>();
^
reason: inferred type does not conform to upper bound(s)
inferred: Test.C
upper bound(s): Test.C>,Test.C
where CAP#1 is a fresh type-variable:
CAP#1 extends Test.C from capture of ?
新類型推斷實(shí)現(xiàn)還存在一個(gè)性能問題(JDK-8051946),該問題可能會(huì)影響使用菱形運(yùn)算符的代碼。如果使用菱形運(yùn)算符,下面的示例將花費(fèi)幾分鐘的時(shí)間進(jìn)行編譯。
class Test {
< T > T and(T a, T b) { return null; }
class C< T > {}
void g(String s) {}
void g(Object s) {}
void m() {
g(
and(
and(
and(
and(
and(
and(
and(new C<>(),
new C<>()),
new C<>()),
new C<>()),
new C<>()),
new C<>()),
new C<>()),
new C<>()));
}
}
加一; 這樣的答案會(huì)讓您超越Jon Skeet。
好的解釋+1
總結(jié)
以上是生活随笔為你收集整理的java diamond 有什么用_Diamond语法何时在Java 8中不起作用?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js之 foreach, map, ev
- 下一篇: eclipse tomcat新建一个_J