Inspectopedia
 
2024.3

Null value for Optional type

Warning
New
Last modified: 03 December 2024

Reports null assigned to an Optional variable or returned from a method returning Optional.

It's recommended that you use Optional.empty() (or Optional.absent() for Guava) to denote an empty value.

Example:

After the quick-fix is applied:

Configure the inspection:

Use the Report comparison of Optional with null option to also report comparisons like optional == null. While in rare cases (e.g. lazily initialized optional field) this might be correct, optional variable is usually never null, and probably optional.isPresent() was intended.

New in 2017.2

This inspection depends on the Java feature 'Stream and Optional API', which is available since Java 8.