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

Viewed 3159

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?

4 Answers

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);

The correct way to do it would be

Optional<Integer> numberOpt = Optional.ofNullable(new Integer(10));
Integer number = Optional.ofNullable(new Integer(10));

With this you are try to put an Optional<Integer> to an Integer. Which is obviously not allowed.

When you do

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

With you are invoking Optional<Integer>.orElse and since you are not using Optional<Integer>.get this returns an Integer. So no errors.

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?

Optional.ofNullable() will return the Optional Object which will hold the actual value we have passed in as a parameter into into instance variable called value.

orElse(T other) - Return the value if present, otherwise returns the object passed as a parameter. Internals of orElse() method in Java 8 Optional class.

public T orElse(T other) {
   return value != null ? value : other;
}

orElse takes the parameter which is Generics and the type casting is performed implicitly. orElse will return the value if its not null otherwise returns the other value which was passed as an parameter.

Related