Kevin
Kevin

Reputation: 6292

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

  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?

Upvotes: 5

Views: 4036

Answers (4)

Daniel Reina
Daniel Reina

Reputation: 6377

From this wiki from google/guava repo, you should use

Optional.absent()

@Dušan already wrote it in a comment to another answer, but I guess this way it will be easier to be found by other people

Upvotes: -1

Mechanical snail
Mechanical snail

Reputation: 30647

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).

Upvotes: 1

darrengorman
darrengorman

Reputation: 13114

Use Optional.fromNullable(T nullableReference)

Upvotes: 1

jlordo
jlordo

Reputation: 37813

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".

[...]

Upvotes: 1

Related Questions