Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional<> and return type narrowing

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?

like image 342
leventov Avatar asked Apr 25 '15 19:04

leventov


People also ask

What is optional return type?

The Optional type was introduced in Java 8. It provides a clear and explicit way to convey the message that there may not be a value, without using null. When getting an Optional return type, we're likely to check if the value is missing, leading to fewer NullPointerExceptions in the applications.

Can optional get return null?

Optional Class is a container for an object that may contains null . With this Optional class, we can semantically told clients that a function they will use may return a null value that lead into NullPointerException .

What is optional in JPA?

Optional is a container object which may or may not contain a non-null value. You must import java. util package to use this class. If a value is present, isPresent() will return true and get() will return the value.

What is the use of optional in Java?

Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.


1 Answers

You could use wildcards.

interface Sup { Optional<? extends A> a(); }

interface Sub extends Sup { Optional<? extends B> a(); }

I could have made it just Optional<B> but using Optional<? extends B> allows another interface to extend Sub and do the same thing.

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.

like image 59
Paul Boddington Avatar answered Oct 12 '22 23:10

Paul Boddington