Why can't the extended operator infer the type of the lambda?
try-with-resource
can infer the type of lambda.
try (Closeable 最後に実行 = () -> System.out.print("終了")) {
System.out.println("開始");
}
But the operator enhanced-for
cannot.
Iterator<String> 繰り返し = Arrays.asList("いち", "に", "さん").iterator();
for (String 文字列 : () -> 繰り返し) // compile error!
System.out.println(文字列);
We have to write like this.
Iterator<String> 繰り返し = Arrays.asList("いち", "に", "さん").iterator();
for (String 文字列 : (Iterable<String>)() -> 繰り返し)
System.out.println(文字列);
Why?
source to share
Try-with-resorce can infer because you have declared the expected result type:
try (Closeable 最後に実行 = () -> System.out.print("終了")) {
^^^^^^^^^
Javac knows the type of the target from this variable assignment that this lambda should be converted to Closeable
. However, in an improved form, there is no such information about the target type. There can be several target types:
-
Iterable<String>
sure -
public interface StringIterable extends Iterable<String>
-
public interface WeridIterable extends Iterable<String>
- ...
There are an arbitrary number of possible target types, so you must explicitly specify it with (Iterable<String>)
, as you did with try-with-resource.
source to share