Optional.orElse does not compile with anonymous types
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);
Case compiles1
Your Optional
has the generic type Bar
, because the variable bar
has type Bar
.
The anonymous class of type Foo$1
you create has Bar
as a super type, thus the method compiles.
Case doesNotCompile
Here, Optional
has the generic type Foo$1
and you are trying to pass an object of type Foo$2
into orElse
which does not have Foo$1
as a super type. Hence the compile error.
Case doesNotCompile2
Similar to doesNotCompile
, Optional
has the generic type Foo$1
and you are trying to pass bar
, a variable of type Bar
into orElse
which again does not have Foo$1
as a super type.
Avoiding these errors
Add a type witness to your call of Optional::of
. This gives your Optional
the generic type Bar
:
public class Foo {
interface Bar {
}
void doesNotCompile() {
Optional.<Bar>of(new Bar() {
}).orElse(new Bar() {
});
}
void doesNotCompile2() {
final Bar bar = new Bar() {
};
Optional.<Bar>of(new Bar() {
}).orElse(bar);
}
void compiles1() {
final Bar bar = new Bar() {
};
Optional.of(bar).orElse(new Bar() {
});
}
}