Queries about records

Vikram Bakshi vab2048 at gmail.com
Wed Dec 23 16:58:25 UTC 2020


Hello,

I have a number of queries about the new Java record feature.

1. What exactly is the reason that the canonical constructor must have the
same access as the record?

Consider the following use case: the record is intended to be a dumb-data
carrier of its validated fields but the validation cannot take place in the
record's constructor because we require access to some elaborate validator
objects to actually perform the validation.

So I thought a way to solve this would be to create the record as public
and the canonical constructor as package-private. Then we have a record
'factory' in the same package which performs the actual validation and
creation of the record. However this is not allowed currently because it
violates the constraint that the canonical constructor must have the same
access as the record itself.

I was just wondering why this constraint?

2. Is there a shorthand to declaring a record field must be non-null?

So for the case where we do not want to allow null in a record field we
have to implement our own logic in the canonical constructor and call
`Objects.requireNonNull(...)`. Is there a way to declare in the record
signature itself that we want it to be non-null to avoid this boilerplate?

3. What exactly is the difference between a static record and non-static
record?

I find myself creating a whole bunch of public records within a single
class. Is there actually any need to mark them as static?

Thanks very much for creating records - they make coding a lot more fun and
allow for writing much more beautiful Java.

Regards,
vab2048


More information about the amber-dev mailing list