Saturday 31 August 2013

How to save null value in Guava Optional

How to save null value in Guava Optional

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
Something that does not have a value
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?

No comments:

Post a Comment