[英]Why enhanced-for statement cannot infer the type of lambda?
try-with-resource
语句可以推断lambda的类型。
try (Closeable 最後に実行 = () -> System.out.print("終了")) {
System.out.println("開始");
}
但enhanced-for
声明不能。
Iterator<String> 繰り返し = Arrays.asList("いち", "に", "さん").iterator();
for (String 文字列 : () -> 繰り返し) // compile error!
System.out.println(文字列);
我们必须这样写。
Iterator<String> 繰り返し = Arrays.asList("いち", "に", "さん").iterator();
for (String 文字列 : (Iterable<String>)() -> 繰り返し)
System.out.println(文字列);
为什么?
Try-with-resorce可以推断,因为您已声明了预期的结果类型:
try (Closeable 最後に実行 = () -> System.out.print("終了")) {
^^^^^^^^^
Javac知道该变量赋值的目标类型,该lambda应转换为Closeable
。 但是在增强中没有这样的目标类型信息。 可能有多种目标类型:
Iterable<String>
public interface StringIterable extends Iterable<String>
public interface WeridIterable extends Iterable<String>
有任意数量的可能目标类型,因此您必须使用(Iterable<String>)
显式地给它,就像在try-with-resource情况下一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.