Type a record with a compact constructor that validates and normalises
Type a record with a compact constructor that validates and normalises
Answer
public record SaleRecord(String productId, double amount, String region) { public SaleRecord { if (amount < 0) throw new IllegalArgumentException("negative amount"); region = region.trim().toUpperCase(); } }
The compact constructor body runs before field assignment. You can validate (throw on bad input) and normalise (reassign region) here. The compiler assigns all components to their fields after the body completes.