I encountered a weird problem using Optional
s and anonymous classes:
public class Foo {
interface Bar {
}
void doesNotCompile() {
Optional.of(new Bar() {
}).orElse(new Bar() {
});
}
void doesNotCompile2() {
final Bar bar = new Bar() {
};
Optional.of(new Bar() {
}).orElse(bar);
}
void compiles1() {
final Bar bar = new Bar() {
};
Optional.of(bar).orElse(new Bar() {
});
}
}
The first two methods do not compile with the error
java: incompatible types: <anonymous test.Foo.Bar> cannot be converted to <anonymous test.Foo.Bar>
I'd expected that, since both implement the interface Bar
all three approaches work. I also cannot figure out why the third option fixes the problem. Can anyone explain this please?
Optional.of
is fixed toOptional<Bar>
. In all the other cases, it isOptional<SubAnonymousSubclassOfBar>
. I would have expected the other two to type-infer the appropriate common upper-bound ofBar
as well, though. But apparentlyOptional<SomeSubclassOfBar>(bar).orElse(someOtherSubclassOfBar)
needs some hand-holding. – Insolvable