@NullMarked with record constructor validation bug?

已回答

Hello

Is this a bug? I intend to use NullMarked to tell users of this class that the fields are non-null, but I want to do validation in the constructor. When i do that it says the condition is always false.

Thanks,

Logan

0
This looks like the expected behavior.

means all reference types are non-null by default. So IntelliJ assumes latitude, longitude, and heading can never be null, which makes:

if (latitude == null)


always false by contract.

How to do validation correctly:

If you want to validate inputs, mark the constructor parameters as nullable:

public record BusCoordinates(
    BigDecimal latitude,
    BigDecimal longitude,
    Integer heading
) {
    public BusCoordinates(
        @Nullable BigDecimal latitude,
        @Nullable BigDecimal longitude,
        @Nullable Integer heading
    ) {
        this.latitude = Objects.requireNonNull(latitude, "latitude must not be null");
        this.longitude = Objects.requireNonNull(longitude, "longitude must not be null");
        this.heading = Objects.requireNonNull(heading, "heading must not be null");
    }
}


This keeps:

fields non-null (API guarantee)

constructor validation meaningful
0

请先登录再写评论。