I've come across an oddity I can't explain.
The following code (a minimal example) won't compile:
class Test {
interface I {}
Optional<I> findOne(ArrayList<? extends I> list) {
return list.stream()
.findFirst();
}
}
javac (version 11 at least) says:
error: incompatible types: Optional<CAP#1> cannot be converted to Optional<I>
.findFirst();
^
where CAP#1 is a fresh type-variable:
CAP#1 extends I from capture of ? extends I
However, I sort of randomly found that adding a seemingly redundant .map() call to the stream [edit: it's actually added to the Optional returned by findFirst()] compiles fine:
class Test {
interface I {}
Optional<I> findOne(ArrayList<? extends I> list) {
return list.stream()
.findFirst()
.map(a -> a);
}
}
I'm curious about what is happening there that adding the .map() call lets it compile.
[I know that changing the method parameter to take an ArrayList<I> works, but that's not what I'm asking about.]