How to keep null in Guava

I am new to the Guava library.

I am trying to use an option in method arguments. One of the problems that I discovered is that I cannot pass null to Optional.

I think the purpose of introducing the Optional is to distinguish between

  • Something that doesn't matter
  • That which has a null value

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

With this logic, I assume that the option must have some way to allow us to store 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)); 

This will give me a runtime error that the value cannot be null.

How can I pass null inside optional?

+4
source share
4 answers

I think this is an intentional limitation.

Optional is an implementation, possibly a monad . This is intended to replace zeros with a safe type, ensuring that if a parameter value is present, you will not get a NullPointerException when you try to use it. Permission to insert null will violate the type security guarantee.

If you really need to distinguish between two types of β€œno data” values, consider Optional<Optional<String>> instead (wrapping your internal possibly-zero data in Option<String> with Optional.fromNullable ).

+1
source

See JavaDoc

An immutable object that may contain a non-zero reference to another object. Each instance of this type either contains a non-zero reference or does not contain anything (in this case we say that the link is "missing"); he never says contain null .

[...]

+1
source

Use Optional.fromNullable(T nullableReference)

0
source

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

 Optional.absent() 

@ Dushan already wrote this in a comment on another answer, but I think it will be easier to find other people

-one
source

Source: https://habr.com/ru/post/1499962/


All Articles