How does this work - Java 8 Optional.of and Optional.ofNullable

user3792861 :

I have question with Java 8 Optionals.

The below code gives compilation error:

Integer number = Optional.ofNullable(new Integer(10)); 

But when we do the following it does not, I don't understand how this is working:

Integer number = Optional.ofNullable(new Integer(10)).orElse(10); 

If we look at the documentation of Optional.ofNullable(), it returns an object of the type static <T> Optional<T> ofNullable(T value) which signifies that it is internally type casting, but the documentation says it return type is Optional.

I get that the .orElse method return type is T which would work fine if it goes to orElse condition, i.e in case the passed in object is null, but if it is not null how does it typecast it?

Ravindra Ranwala :

Take a look at the declaration of the method,

public static <T> Optional<T> ofNullable(T value)

So this takes T and returns Optional<T> So in your case it takes Integer and returns an Optional<Integer>

So when you do this,

Optional.ofNullable(new Integer(10)).orElse(10);

The orElse call will unwrap the optional and returns the value in it if it is not empty. Otherwise it merely returns the given value.

Update

As per the following comments you can simplify it further while leaving the job to the Autoboxing.

Optional.ofNullable(10).orElse(10);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85546&siteId=1