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(); }
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(); }
But doesn't compile! Because Optional<B>
is not a subclass of Optional<A>
.
How I'm supposed to resolve this issue?
Optional
paradigm produces fewer NPEs, and forces one to reason better about what behaviors the code actually has. – Neoma