typestar

Records in Java

A whole value class in one line.

var current = new Semver(21, 0);
var again = new Semver(21, 0);

System.out.println(current);                // records print themselves
System.out.println(current.equals(again));  // and compare by value
System.out.println(current.major());        // accessors take the field names
System.out.println(current.tag());

record Semver(int major, int minor) {
    String tag() { return "v" + major + "." + minor; }
}

How it works

  1. record Semver(int major, int minor) declares fields and all.
  2. Records print themselves and compare by value.
  3. Accessors take the field names; extra methods are allowed.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
409
Tokens
104
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 3 of 4 in Classes & records, step 20 of 29 in Language basics.

← Previous Next →

Records in other languages