Question about type pattern inside record pattern

Remi Forax forax at univ-mlv.fr
Fri Feb 6 16:51:48 UTC 2026


----- Original Message -----
> From: "cay horstmann" <cay.horstmann at gmail.com>
> To: "amber-dev" <amber-dev at openjdk.org>
> Sent: Friday, February 6, 2026 5:00:36 PM
> Subject: Question about type pattern inside record pattern

> Consider this program:
> 
> record Amount(Number n) {}
> 
> Integer value(Amount p) {
>     return switch (p) {
>         case Amount(Integer value) -> value;
>         case Amount(Number _) -> -1;
>         case Amount(Object _) -> -2;
>     };
> }
> 
> void main() {
>     IO.println(value(new Amount(null)));
> }
> 
> It prints -1.
> 
> I have two questions:
> 
> 1. Why does it compile? The case Amount(Object _) does not seem to reachable.

I don't know :)

> 2. Why does null match case Amount(Number _) and not one of the other?

I can help for this one.

The long story short is that matching at top-level and de-structuring behave differently.

Basically, we want case Amount(var n) or case Amount(Number n) to be equivalent semantically to case Amount _.
So it means that case Amount(Number n) has to match even if n is null.

The other reason is that if it does not behave that way, to be exhaustive, you will have to add case Amount(null), which does not scale once you start to de-structure several components because you have to add all the combinations.

In the future, if you want to not match null, you will be able to write case Amount(Number! n) or if you want to only match null, case Amount(null).


> 
> I tried applying JLS (for Java 25) §14.30, §15.28, and §14.11 but could not
> figure it out. Where should I look?
> 
> Thanks,
> 
> Cay

regards,
Rémi

> 
> --
> 
> Cay S. Horstmann | https://horstmann.com


More information about the amber-dev mailing list