Inspectopedia Help

Null value for Optional type

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

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

Example:

Optional<Integer> foo(boolean flag) { return flag ? Optional.of(42) : null; }

After the quick-fix is applied:

Optional<Integer> foo(boolean flag) { return flag ? Optional.of(42) : Optional.empty(); }

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.

This inspection only reports if the language level of the project or module is 8 or higher.

New in 2017.2

Inspection options

Option

Type

Default

Report comparison of Optional with null

Checkbox

true

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3

Plugin:

Java, 233.SNAPSHOT

Last modified: 13 July 2023