Pattern Matching

mit Java 19

Falk Sippach / @sippsack / ✉️

Merlin Bögershausen / @mboegie

Agenda

08:30

30'

🚪 Ankommen and Basics

09:00

60'

👩🏼‍💻 Features Live Demo

10:00

30'

☕️ Pause

10:30

60'

🧑🏽‍💻 Code Together

11:30

30'

⁉️ Fragen und Diskussion

Basics

Einrichtung und Setup

  • JDK 19 installieren

  • aktuelle IDE (IntelliJ IDEA, Eclipse, Visual Studio Code, …)

    • sollte Java 19 Features unterstützen

    • IntelliJ 2022.2, Eclipse 2022-09 (4.25)

Road to OpenJDK 21 (LTS)

openjdk java 19

Features

features

On the Menu

  • JEP 361: Switch Expression

  • JEP 359: Record Classes

  • JEP 409: Sealed Classes

  • JEP 394: Type (instanceof) Pattern

  • JEP 427: Pattern Matching for switch

  • JEP 405: Record (deconstruction) pattern

JEP 361

Switch Expression

int j = switch (day) {
  case MONDAY, null -> 0;
  case TUESDAY -> 1;
  default -> {
    int k = day.toString().length();
    yield k;
  }
};

JEP 359

Record classes

record Range(List<Integer> values) {
  Range { Objects.requirenNonNull(values); }

  Range(List<Integer> values) {
    this.values = List.copyOf(values);
  }

  Range(Integer i1, Integer i2) {
    this(List.of(i1,i2));
  }

  int length() { return values.length(); }
}

JEP 409

Sealed classes

sealed interface Shape permits Circular, Cornered { }

non-sealed class Circular implements Shape {}

sealed class Cornered implements Shape {
    final class Rectangle implements Cornered {}
  record Square(int h) implements Cornered {}
}

Sealed classes

sealed

JEP 394

Type (instanceof) Pattern

if (o instanceof Triangle t) {
    System.out.println("Area: " + t.calculateArea());
} else if (!(o instanceof String str)) {
    System.out.println("Not Triangle or String ");
} else {
    System.out.println("String value is:" + str);
}

JEP 427

Pattern matching for Switch

switch (s) {
  case Triangle t when t.calculateArea() > 100 ->
    System.out.println("Large");
  case Triangle t -> System.out.println("Small");
  default -> System.out.println("Non-triangle");
}

JEP 405

Record deconstruction pattern

record Point<T>(T x, T y) {}

static <T> void print(Object o) {
  if (o instanceof Point(T x, T y)) {
    System.out.println(x + "+" + y);
  }
}

Example: Single Linked List

Basics

LinkedListBasics.excalidraw

Structure

LinkedListTypes.excalidraw

Operations

LinkedListOperations.excalidraw

Solution Code

Solution und Binärbaum MBoegers/TreeExperiments

Example: BadTelefon

Refactoring

badtelefon

Repo for Hands-on Live-Coding

Final thought

Weitere Infos

Slides 'n' Code