Another syntax for Java records

Remi Forax forax at univ-mlv.fr
Tue Nov 22 22:02:17 UTC 2022


> From: "Heinzl, Steffen" <steffen.heinzl at fhws.de>
> To: "amber-dev" <amber-dev at openjdk.org>
> Sent: Tuesday, November 22, 2022 10:25:20 PM
> Subject: Another syntax for Java records

> Hi!

> I wanted to suggest (if not yet done) to another syntax to Java records.

> I don’t quite understand the idea behind the syntax except that some other
> programming languages do it similar.

> A Java class looks like this:

> public class MyClass

> {

> String s;

> void myMethod(String a, int b);

> }

> An interface looks like this:

> public interface MyInterface

> {

> void myMethod(String c, String d);

> }

> Why all of a sudden is it a good idea to change that syntax to:

> public record MyRecord(String r, int x)

> {

> }

> instead of the following syntax (which is also possible in C# by the way)

> public record MyRecord

> {

> String r;

> int x;

> }

> I’m teaching Java and I find it strange from a lecturer’s point of view to
> explain the rationale for introducing the syntax like that. I’d be glad if
> someone could enlighten me!

Conceptually a record defines components which are more than just fields, a component can not be modified, a component has a public accessor (no encapsulation). 

The canonical constructor, equals/hashCode/toString(), the way to reflect on, use annotation or serialize a record are all defined in term of components. 
The order of the components is also important for the serialization and the canonical constructor. The name of the components is important for the canonical constructor. 

So the syntax reflects the fact that a record is defined by a name and its components. 

see [ https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Record.html | https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Record.html ] 

> Thanks! Best,

> Steffen

regards, 
Rémi 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20221122/f14dfc73/attachment.htm>


More information about the amber-dev mailing list