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(); }

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

OptionalAssignedToNull
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Java | Code maturity

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.

Inspection options

Here you can find the description of settings available for the Null value for Optional type inspection, and the reference of their default values.

Report comparison of Optional with null

Default: Selected

Availability

By default bundled with

IntelliJ IDEA 2024.1, Qodana for JVM 2024.1,

Can be installed with plugin

Java, 241.18072

Last modified: 18 June 2024