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?
You can supplement the type on the first two using a type witness:
Optional.<Bar>of(new Bar(){}).orElse(new Bar(){});
This allows the compiler to see that you are expecting a return of Optional<Bar>
, which #orElse can then inferr to accepting any Bar
You'd need to tell the Optional that you want a Bar for that interface.
Bar bar = new Bar();
Optional<Bar> o = Optional.of(new Bar() {}).orElse(bar);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With