Skip to content

The optional chaining operator for spring POC #37052

Description

@Ahmedhsultan

One of the most common causes of runtime exceptions in Java applications is the NullPointerException generated when traversing deep object graphs.

For example:

String city = user.getAddress().getCountry().getCity().getName();

If any intermediate object is null, the application throws a NullPointerException.

Languages such as TypeScript, JavaScript, Kotlin, C#, and Swift provide an optional chaining operator that allows developers to safely navigate nested objects.

Example in TypeScript:

String city = user?.address?.country?.city?.name;
Proposal

Introduce an annotation such as:

@OptionalOpt
public class User {
private Address address;
}

The annotation processor would generate optional-safe accessor fields or methods with an Opt suffix.

Generated example:

user.addressOpt.countryOpt.cityOpt.nameOpt.get();

or

user.getAddressOpt()
.getCountryOpt()
.getCityOpt()
.getNameOpt()
.orElse(null);
Benefits
Eliminates repetitive null checks.
Reduces NullPointerException occurrences.
Improves readability when traversing deep object graphs.
Provides a developer experience similar to Kotlin and TypeScript optional chaining.
Can be generated at compile time with no reflection overhead.
Existing Proof of Concept

I have already implemented a proof-of-concept library published on maven repository:

io.github.ahmedhsultan NSFOperator 1.17.1

The library generates optional-safe accessors that allow chaining without throwing NullPointerException.

Discussion Points
Would Spring developers find value in compile-time generated optional chaining?
Should this be implemented through annotation processing, Lombok-style code generation, or another mechanism?
Are there concerns regarding API discoverability, performance, or readability?
Could this be a candidate for broader ecosystem adoption alongside records and modern Java language features?

I would appreciate feedback from the community regarding the design, usability, and potential integration approaches.

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: declinedA suggestion or change that we don't feel we should currently apply

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions