可选<>和返回类型变窄 [英] Optional<> and return type narrowing
问题描述
在Java中< 8,返回不安全"对象(objects或null),我能够在子类中专门化返回类型:
In Java < 8, returning "unsafe" objects (objects or null), I was able to specialize return type in subclass:
class A {}
class B extends A {}
interface Sup { A a(); /* returns A instance, or null */ }
interface Sub extends Sup { B a(); }
在Java 8中,如果我想使我的API更安全",则应该返回Optional<A>
而不是"raw" A
:
In Java 8, if I want to make my API "safer", I should return Optional<A>
instead of "raw" A
:
interface Sup { Optional<A> a(); }
interface Sub extends Sup { Optional<B> a(); }
但是不能编译!因为Optional<B>
不是Optional<A>
的子类.
But doesn't compile! Because Optional<B>
is not a subclass of Optional<A>
.
我应该如何解决此问题?
How I'm supposed to resolve this issue?
推荐答案
您可以使用通配符.
interface Sup { Optional<? extends A> a(); }
interface Sub extends Sup { Optional<? extends B> a(); }
我本可以将其设置为Optional<B>
,但是使用Optional<? extends B>
允许另一个接口扩展Sub
并执行相同的操作.
I could have made it just Optional<B>
but using Optional<? extends B>
allows another interface to extend Sub
and do the same thing.
我个人认为这有些混乱,最好在必要时只返回A
或B
或null
.
Personally, I think this is a bit of a mess, and it would be preferable to just return A
or B
, or null
where necessary.
这篇关于可选<>和返回类型变窄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!