We use Lombok in our everyday project and I love it for the brevity it introduced. We have a tone of BigDecimal properties and with a little bit of effort made them ignore the scale in Lombok's generated equals and hashCode methods. Is there a way to do this in new record classes introduced in Java 16?
It sounds like you're after a general way to alter how equals
and hashCode
are implemented for fields that have a specific, existing type. There's no way to do this.
You have two options:
equals
and hashCode
yourself on every record
you define, like:record Test(BigDecimal v) {
public int hashCode() {
return Util.hashCodeWithoutScale(v);
}
public boolean equals(Object o) {
return Util.equalsForBigDecimalWithoutScale(this, o);
}
}
record Test(BigDecimalWrapperThatIgnoresScaleInHashCodeAndEquals x) {
}
For us this feature seems unusable.
While BigDecimal
is close to your requirements, the mismatch in behaviour suggests you may have better luck with use of a wrapper, or an alternate class instead, even if it largely delegates to the existing class.