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
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?
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
).
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
".[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With