Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save null value in Guava Optional

Tags:

java

guava

I am new to Guava library.

I am trying to use Optional in my method arguments. One problem I found is that I cannot possibly pass null value into Optional.

I think the purpose of introducing Optional is to differentiate

  1. Something that does not have a value
  2. Something that has a null value

For example, Optional.absent() means the value does not exist. While null is a value that exist.

With this logic, I assume Optional must have some way to allow us to save a null value in it. However, I could not find a way to do this.

My method is defined as:

void myMethod(Optional<String> arguments) {
    ....
}

If I use

myMethod(Optional.of(null));

It will give me the runtime error says the value cannot be null.

How can I possibly pass null inside an Optional?

like image 900
Kevin Avatar asked Nov 01 '22 15:11

Kevin


2 Answers

I think this is an intentional restriction.

Optional is an implementation of the Maybe monad. This is intended to replace nulls in a type-safe way, guaranteeing that if the option value is present, you won't get a NullPointerException when you try to use it. Allowing you to insert null would break this type-safety guarantee.

If you really need to distinguish two kinds of "no data" value, consider using Optional<Optional<String>> instead (wrapping your inner possibly-null data in an Option<String> by using Optional.fromNullable).

like image 65
Mechanical snail Avatar answered Nov 15 '22 05:11

Mechanical snail


See JavaDoc

An immutable object that may contain a non-null reference to another object. Each instance of this type either contains a non-null reference, or contains nothing (in which case we say that the reference is "absent"); it is never said to "contain null".

[...]

like image 31
jlordo Avatar answered Nov 15 '22 04:11

jlordo