'What is the type of a Java empty Optional?

So the thing is I was checking Optional Java class and I noticed this in the public static<T> Optional<T> empty() doc:

@param <T> The type of the non-existent value*.

And, after looking at the whole class and searching over here and a few other pages I came to this questions that I haven't been able to answer:

  1. Can an empty Optional have a specific type? 1.1 If so, how do you set it? 1.2 And is there any way to check its type?


Solution 1:[1]

The Optional class is a container that might contain a specific element. As such, it has two concepts:

  • The type it might contain
  • The actual object it contains

The type it might contain is specified trough generics. Generics only exist at compile time and are lost at runtime.

To answer your questions:

  1. When using an Optional, you usually define it to possibly contain a type, like this:
Optional<String> optionalString;

At this point we know that optionalString might contain a String. If we do this:

Optional<String> optionalString = Optional.empty();

It doesn't actually contain anything, but we can use it anywhere an Optional<String> is required.

  1. The type of the Optional is inferred trough its usage. Like above, you specify the Optional.empty() to be an Optional<String>. You can also specify its type trough the return value of a method, like so:
public Optional<Integer> findNumber() {
    return Optional.empty();
}
  1. Since the type is no longer present at runtime, there is no way to check what the optional contains at this point. At runtime, an empty Optional has no type.

Solution 2:[2]

It's whatever type you specify:

// Empty Optional with value type String
Optional<String> opt = Optional.empty();

Here is the source code for that method from OpenJDK 11:

    public static<T> Optional<T> empty() {
        @SuppressWarnings("unchecked")
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
    }

EMPTY is a static instance (from the source code linked above):

    /**
     * Common instance for {@code empty()}.
     */
    private static final Optional<?> EMPTY = new Optional<>();

Solution 3:[3]

I know a Link to a Blogpost has already been posted, but I always refer back to this on: Baeldung Java Optional 8

To ur questions:

  1. Optional can contain any Object type(if u need an int then use Integer)

  2. Optional.of(urObject) now the "type" is Optional

  3. No u can't check the type of the Optional.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Paul
Solution 3 robson90