java - Optional<> and return type narrowing -


in java < 8, returning "unsafe" objects (objects or null), able specialize return type in subclass:

class {} class b extends {} interface sup { a(); /* returns instance, or null */ } interface sub extends sup { b a(); } 

in java 8, if want make api "safer", 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> not subclass of optional<a>.

how i'm supposed resolve issue?

you use wildcards.

interface sup { optional<? extends a> a(); }  interface sub extends sup { optional<? extends b> a(); } 

i have made optional<b> using optional<? extends b> allows interface extend sub , same thing.

personally, think bit of mess, , preferable return a or b, or null necessary.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -