Extremely Serious

Category: Java 16

Type Pattern Matching for instanceof

The pattern matching enhancement that conditionally extract data from an object if the instanceof operator was satisfied and assigns it to a variable.

The variable in this pattern matching is following a flow scope. This means that the variable is in scope if it is guaranted that it can satisfies the instanceof operator.

Code Without Pattern Matching

record Person(String firstName, String lastName) {}

Record rec = new Person("Juan", "Dela Cruz");

//Check if rec is a Person.
if (rec instanceof Person) {

    //rec can safely be casted to Person.
    var person = (Person) rec;

    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that casting the rec to Person once the check succeded is required.

Code With Pattern Matching

record Person(String firstName, String lastName) {}

Record rec = new Person("Juan", "Dela Cruz");

//If rec is a Person extract it to a variable person.
if (rec instanceof Person person) {
    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that casting is not required here and Person instance is extracted to person variable. Moreover, the scope of the variable is in the truth block of the if statement.

Flow Scope

Example 1

Record rec = new Person("Juan", "Dela Cruz");

if (!(rec instanceof Person person)) {
    System.out.println("In human.");
}
else {
    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that person variable usage is on the else block of the if statement.

Example 2

Record rec = new Person("Juan", "Dela Cruz");

if (rec instanceof Person person && "JUAN DELA CRUZ".equals(String.join(person.firstName(), " ", person.lastName().toUpperCase()))) {
    System.out.println("You won a price");
}

Notice that the person variable is usable after the AND (&&) operator. This is because the and operator guarantees that the instanceof operator was satisfied before evaluating the following condition. Changing it to OR (||) operator will be an error, since the person variable is out of scope.

Practical Usage

equals implementation

import java.util.Objects;

record Person(String firstName, String lastName) {

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (null == o) return false;
        if (o instanceof Person person) {
            return Objects.equals(firstName, person.firstName()) && Objects.equals(lastName, person.lastName());
        }
        return false;
    }

}

Record Class

A record class is a restricted form of classes that models data as data. Thus, also can be thought as data only class. Additionally, this type of class is immutable.

It automatically implements the following methods:

  • public boolean equals...
  • public int hashCode...
  • public String toString() {...}

The class generated by the record is a final class.

The constructor will also be handled and the parameters is matching the arrangement of the record parameter(s).

Use Cases

  • Data Transfer Objects (DTO) (i.e. not applicable to JPA entities)
  • Compound map keys
  • Multiple return values

Syntax

record <IDENTIFIER>([[[<FIELD_TYPE_1> <FIELD_NAME_1>][, <FIELD_TYPE_2> <FIELD_NAME_2>]][,... <FIELD_TYPE_2> <FIELD_NAME_N>]]) {}
Token Description
IDENTIFIER A valid Java identifier.
FIELD_TYPE_1
FIELD_TYPE_2
FIELD_TYPE_N
The type of the field(s) in the record parameter(s).
FIELD_NAME_1
FIELD_NAME_2
FIELD_NAME_N
The name of the field(s) in the record parameter(s).

The identifier has an equivalent cannonical constructor with parameters equivalent to its parameters.

Each fields has the following:

  • private final field of the same name.
  • public accessor method of the same name and type.

Example

record Person(String firstName, String lastName) {}

The above example is equivalent to the following class definition:

public final class PersonC {

    private final String firstName;
    private final String lastName;

    public PersonC(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() {
        return this.firstName;
    }

    public String lastName() {
        return this.lastName;
    }

    public boolean equals...
    public int hasCode...
    public String toString() {...}

}

Compact Constructor

In the record definition we can use a compact constructor. This constructor is the shorthand form of the generated default constructor. All of the fields indicated on the record parameters are implicitly available in it.

Syntax of the Compact Constructor

pubic <IDENTIFIER> {
    // Initilization logic.
}

The IDENTIFIER here is matching the record IDENTIFIER, just like when you are writing a constructor of a class but without parameters even the parentheses.

Example Usage

record Person(String firstName, String lastName) {
    public Person {
        java.util.Objects.requireNonNull(firstName);
        java.util.Objects.requireNonNull(lastName);
    }
}