Optional null value with a type

Viewed 1075

Is there a more concise way of creating an Optional.ofNullable of specified type without assigning it to the variable?

The working solution:

public Optional<V> getValue2(K key) {
    Node<K, V> node = getNode(key);
    Optional<V> nullable = Optional.ofNullable(null);
    return isNull(node) ? nullable : Optional.ofNullable(node.getValue());
} 

Here I get an error: "Type mismatch: cannot convert from Optional to Optional"

public Optional<V> getValue(K key) {
    Node<K, V> node = getNode(key);
    return isNull(node) ? Optional.ofNullable(null) : Optional.ofNullable(node.getValue());
}
2 Answers

Basically, a simpler way would be:

public Optional<V> getValue(K key) {
    return Optional.ofNullable(getNode(key))
                   .map(Node::getValue);
}  

If you still want to stick with what you had, you could do it with:

public Optional<V> getValue(K key) {
    Node<K, V> node = getNode(key);
    return isNull(node) ? 
            Optional.empty() : Optional.ofNullable(node.getValue());
}

I think you are looking for this:

Optional.<V>ofNullable(null);

or in your case, if there is always a null passed:

Optional.<V>empty();    
Related