Skip to content

Commit cfbeb24

Browse files
committed
Code for the Pattern Matching article
Every listing of the article as a compact source file of its own, so `java <file>` prints exactly the output the article shows. Runs on Java 25 and 27 with identical output; the article quotes javac 27. The listings that show a compiler error live in does-not-compile/, the primitive-type-pattern example in preview/, both outside the Maven build. Spotless checks whitespace only: the switch arrows are aligned as in the article, and google-java-format would collapse that. The SonarQube Cloud project does not exist yet; the workflow skips the Sonar step without a token.
1 parent d766ba9 commit cfbeb24

54 files changed

Lines changed: 968 additions & 1 deletion

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/dependabot.yml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
version: 2
2+
updates:
3+
# Enable version updates for GitHub Actions
4+
- package-ecosystem: "github-actions"
5+
directory: "/"
6+
schedule:
7+
interval: "daily"
8+
9+
# Enable version updates for Maven
10+
- package-ecosystem: "maven"
11+
directory: "/"
12+
schedule:
13+
interval: "daily"

‎.github/workflows/build.yml‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
name: build
2+
3+
on:
4+
push:
5+
branches: [ main ]
6+
pull_request:
7+
branches: [ main ]
8+
9+
jobs:
10+
build-jvm:
11+
name: Build
12+
13+
runs-on: ubuntu-latest
14+
15+
steps:
16+
- name: Checkout code
17+
uses: actions/checkout@v7
18+
with:
19+
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
20+
21+
# The sources are on maven.compiler.source/target 25: the listings use
22+
# main() without arguments (final in Java 25). Dependabot keeps raising
23+
# the plugin versions, each with its own JDK floor, without knowing which
24+
# JDK the workflow uses.
25+
- name: Set up JDK
26+
uses: actions/setup-java@v6
27+
with:
28+
# 'adopt' was the AdoptOpenJDK alias; setup-java dropped it after the
29+
# project became Eclipse Temurin. Dependabot keeps the action version
30+
# current but cannot know that an input value went away.
31+
distribution: 'temurin'
32+
java-version: 25
33+
34+
- name: Cache SonarCloud packages
35+
uses: actions/cache@v6
36+
with:
37+
path: ~/.sonar/cache
38+
key: ${{ runner.os }}-sonar
39+
restore-keys: ${{ runner.os }}-sonar
40+
41+
- name: Cache Maven packages
42+
uses: actions/cache@v6
43+
with:
44+
path: ~/.m2
45+
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
46+
restore-keys: ${{ runner.os }}-m2
47+
48+
- name: Verify code format
49+
run: mvn -B spotless:check
50+
51+
- name: Compile, test and verify
52+
run: mvn -B verify -Ptest-coverage
53+
54+
- name: Analyze code with Sonar
55+
if: ${{ env.SONAR_TOKEN }} # the token is not available in Dependabot-triggered builds
56+
env:
57+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
58+
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
59+
run: mvn -B org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
name: dependabot auto-merge
2+
# Using a short name here for two reasons:
3+
# 1) The "Workflows" column on the "Actions" tab is quite narrow
4+
# 2) The name is used as label on the README badge
5+
6+
on: pull_request
7+
8+
permissions:
9+
pull-requests: write
10+
contents: write
11+
12+
jobs:
13+
dependabot:
14+
runs-on: ubuntu-latest
15+
if: ${{ github.actor == 'dependabot[bot]' }}
16+
steps:
17+
- name: Dependabot metadata
18+
id: metadata
19+
# Pinned to the commit, not the tag: a tag can be moved, and this
20+
# workflow hands the action a token with contents: write.
21+
# Dependabot keeps SHA pins current and updates the comment with them.
22+
uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0
23+
with:
24+
github-token: "${{ secrets.GITHUB_TOKEN }}"
25+
26+
- name: Approve a PR
27+
run: gh pr review --approve "$PR_URL"
28+
env:
29+
PR_URL: ${{github.event.pull_request.html_url}}
30+
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
31+
32+
- name: Enable auto-merge for Dependabot PRs
33+
if: ${{ steps.metadata.outputs.update-type != 'version-update:semver-major' }}
34+
run: gh pr merge --auto --rebase "$PR_URL"
35+
env:
36+
PR_URL: ${{github.event.pull_request.html_url}}
37+
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}

‎.gitignore‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
.classpath
2+
.idea
3+
.project
4+
.settings
5+
out
6+
target
7+
**/gitignore
8+
*.iml
9+
*.class
10+
.junie

‎README.md‎

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,82 @@
1-
# java-pattern-matching
1+
# Pattern Matching in Java
2+
3+
[![Build](https://github.com/SvenWoltmann/java-pattern-matching/actions/workflows/build.yml/badge.svg)](https://github.com/SvenWoltmann/java-pattern-matching/actions/workflows/build.yml)
4+
[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=SvenWoltmann_java-pattern-matching&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=SvenWoltmann_java-pattern-matching)
5+
[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=SvenWoltmann_java-pattern-matching&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=SvenWoltmann_java-pattern-matching)
6+
[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=SvenWoltmann_java-pattern-matching&metric=security_rating)](https://sonarcloud.io/dashboard?id=SvenWoltmann_java-pattern-matching)
7+
8+
## Article
9+
10+
The code refers to the following articles (not yet published):
11+
* English: [Pattern Matching in Java: instanceof, switch, and Record Patterns](https://www.happycoders.eu/java/pattern-matching/)
12+
* German: [Pattern Matching in Java: instanceof, switch und Record Patterns](https://www.happycoders.eu/de/java/pattern-matching/)
13+
14+
## Contents
15+
16+
Every listing of the article is a compact source file of its own and prints the output shown there. The files need Java 25 or newer – compact source files and the `IO` class are final since Java 25 – even though the features they show are older. Run one directly from the repository root:
17+
18+
```
19+
java src/main/java/Intro.java
20+
```
21+
22+
`mvn compile` compiles all of them at once.
23+
24+
The folders, in the order of the article:
25+
26+
* `src/main/java/` – the runnable listings, e.g. `InstanceofPattern` (Pattern Matching for instanceof), `SwitchTypePatterns` and `SwitchCaseNull` (Pattern Matching for switch), `ExhaustiveSealed` (a switch over a sealed interface without `default`), `NestedRecordPattern` and `RecordPatternNull` (record patterns), and `Expressions` (an expression tree of records with `eval()`, `format()` and `simplify()`)
27+
* `does-not-compile/` – the listings the article shows with a compiler error; the first line of each file names the error. Compile one with `javac -d /tmp does-not-compile/ScopeWithOr.java` to see it. The messages in the article come from `javac` 27; up to Java 26, the "missing patterns" lines are not printed.
28+
* `preview/` – primitive type patterns, a preview feature in Java 23 to 27: `java --enable-preview preview/PrimitiveTypePatterns.java`
29+
30+
`SwitchWithoutCaseNull` ends with a `NullPointerException` on purpose: the article shows what a `switch` without `case null` does with `null`.
31+
32+
33+
<!-- happycoders-resources:start -->
34+
<!-- Generated from happycoders-website-astro/data/github-readme by scripts/content/sync-github-readmes.mjs. Edit there, not here. -->
35+
36+
## <br>Additional Resources
37+
38+
### <br>Java Versions PDF Cheat Sheet
39+
40+
**Stay up-to-date** with the latest Java features with this **free** [PDF Cheat Sheet](https://www.happycoders.eu/java-versions/)!
41+
42+
[<img src="/img/java-versions-cheat-sheet-mockup.png" alt="Java Versions PDF Cheat Sheet Mockup" width="468">](https://www.happycoders.eu/java-versions/)
43+
44+
* Avoid lengthy research with this **concise overview of all Java versions from Java 10 to Java 27**.
45+
* **Discover the innovative features** of each new Java version, summarized on a single page.
46+
* **Impress your team** with your up-to-date knowledge of the latest Java version.
47+
48+
👉 [Download the free Java Versions PDF](https://www.happycoders.eu/java-versions/)<br>
49+
50+
_(Hier geht's zur deutschen Version &rarr; [Java-Versionen PDF](https://www.happycoders.eu/de/java-versionen/))_
51+
52+
53+
### <br>The Big O Cheat Sheet
54+
55+
With this **free** [1-page PDF cheat sheet](https://www.happycoders.eu/big-o-cheat-sheet/), you'll always have the **7 most important complexity classes** at a glance.
56+
57+
[<img src="/img/big-o-cheat-sheet-mockup.png" alt="Big O PDF Cheat Sheet Mockup" width="304">](https://www.happycoders.eu/big-o-cheat-sheet/)
58+
59+
* **Always choose the most efficient data structures** and thus increase the performance of your applications.
60+
* **Be prepared for technical interviews** and confidently present your algorithm knowledge.
61+
* **Become a sought-after problem solver** and be known for systematically tackling complex problems.
62+
63+
👉 [Download the free Big O Cheat Sheet](https://www.happycoders.eu/big-o-cheat-sheet/)<br>
64+
65+
_(Hier geht's zur deutschen Version &rarr; [O-Notation Cheat Sheet](https://www.happycoders.eu/de/o-notation-cheat-sheet/))_
66+
67+
68+
### <br>HappyCoders Newsletter
69+
👉 Want to stay on top of modern Java?
70+
Sign up for the [HappyCoders newsletter](https://www.happycoders.eu/newsletter/) – Modern Java: new versions & features, performance, and JVM insights – once a month.
71+
72+
_(Hier geht's zur deutschen Version &rarr; [HappyCoders-Newsletter deutsch](https://www.happycoders.eu/de/newsletter/))_
73+
74+
75+
### <br>🇩🇪 An alle Java-Entwickler:innen, die durch fundierte Kenntnisse über Datenstrukturen besseren Code schreiben wollen
76+
77+
Trage dich jetzt unverbindlich auf die [Warteliste](https://www.happycoders.eu/de/mastering-data-structures-warteliste/) von „Mastering Data Structures in Java“ ein, und erhalte das beste Angebot!
78+
79+
[<img src="/img/mastering-data-structures-product-mockup.png" alt="Mastering Data Structures Mockup" width="640">](https://www.happycoders.eu/de/mastering-data-structures-warteliste/)
80+
81+
👉 [Zur Warteliste](https://www.happycoders.eu/de/mastering-data-structures-warteliste/)
82+
<!-- happycoders-resources:end -->
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Does not compile: this case label is dominated by a preceding case label
2+
3+
String greet(String text) {
4+
return switch (text) {
5+
case String s -> "text: " + s;
6+
case "Hello" -> "Hello back";
7+
};
8+
}
9+
10+
void main() {}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Does not compile: this case label is dominated by a preceding case label
2+
3+
String describe(Object obj) {
4+
return switch (obj) {
5+
default -> "something else";
6+
case String s -> "string: " + s;
7+
};
8+
}
9+
10+
void main() {}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Does not compile: this case label is dominated by a preceding case label
2+
3+
String describe(Object obj) {
4+
return switch (obj) {
5+
case String s -> "string: " + s;
6+
case String s when s.length() > 5 -> "long string: " + s;
7+
default -> "something else";
8+
};
9+
}
10+
11+
void main() {}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Does not compile: this case label is dominated by a preceding case label
2+
3+
String describe(Object obj) {
4+
return switch (obj) {
5+
case Number n -> "number: " + n;
6+
case Integer i -> "integer: " + i;
7+
default -> "something else";
8+
};
9+
}
10+
11+
void main() {}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Does not compile: illegal fall-through to a pattern
2+
3+
void print(Object obj) {
4+
switch (obj) {
5+
case Integer i:
6+
IO.println("integer: " + i);
7+
case String s:
8+
IO.println("string: " + s);
9+
break;
10+
default:
11+
IO.println("something else");
12+
}
13+
}
14+
15+
void main() {}

0 commit comments

Comments
 (0)