我在使用Java Optionals和匿名类时遇到了一个奇怪的问题:
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() {
});
}
}
前两个方法没有编译错误java: incompatible types: <anonymous test.Foo.Bar> cannot be converted to <anonymous test.Foo.Bar>
我希望,因为这两种方法都实现了接口Bar
,所以所有这三种方法都可以工作。我也无法弄清楚为什么第三个选项可以解决此问题。谁能解释一下?
您需要告诉Optional,您想要该接口的Optional。这就是泛型的用途...
Bar bar = new Bar();
Optional<Bar> o = Optional.of(new Bar {}).orElse(bar);