Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
}
like image 715
marekmuratow Avatar asked Sep 02 '18 10:09

marekmuratow


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());
}
like image 189
Eugene Avatar answered Oct 13 '22 00:10

Eugene


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();    
like image 3
MaanooAk Avatar answered Oct 13 '22 00:10

MaanooAk