marekmuratow
marekmuratow

Reputation: 404

Optional null value with a type

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

Upvotes: 6

Views: 1312

Answers (2)

Eugene
Eugene

Reputation: 120848

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

Upvotes: 7

MaanooAk
MaanooAk

Reputation: 2468

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

Upvotes: 5

Related Questions