# Draft JEP on pattern matching

Mark Raynsford org.openjdk at io7m.com
Sun Jun 4 13:52:55 UTC 2017

```On 2017-06-02T13:47:25 -0400
Brian Goetz <brian.goetz at oracle.com> wrote:

> I've published a draft JEP on the first phase of Pattern Matching here:
>
>      https://bugs.openjdk.java.net/browse/JDK-8181287
>
> Additional notes on our explorations can be found at:
>
>      http://cr.openjdk.java.net/~briangoetz/amber/pattern-match.html
>      http://cr.openjdk.java.net/~briangoetz/amber/switch-rehab.html
>
> After there's been a chance for public comment, I'll be aiming to submit
> this JEP next week.
>

This looks good to me as a first step. I'm curious about the semantics
of the new switch statement.

Haskell and friends have the behaviour that the matches are
conceptually evaluated from top to bottom:

data T = A | B | C

f :: T -> Integer
f x =
case x of
A -> 0
B -> 1
C -> 2

So:

f A ⇒ 0
f B ⇒ 1
f C ⇒ 2

However:

f :: T -> Integer
f x =
case x of
_ -> 0
B -> 1
C -> 2

This would yield (with various compilation warnings):

f A ⇒ 0
f B ⇒ 0
f C ⇒ 0

... because the _ pattern matches anything and, as the branches are
conceptually evaluated from top to bottom, the B and C patterns are
unreachable.

So:

f :: T -> Integer
f x =
case x of
A -> 0
_ -> 1

Would yield:

f A ⇒ 0
f B ⇒ 1
f C ⇒ 2

Java's existing switch statement obviously doesn't do this: The branch
of the switch that matches exactly is the only one that's evaluated.
I'm curious how the new switch statement would change these semantics.
How would the following behave with guards?

switch (c) {
case Integer i && i >= 0: return 1;
case Integer i && i >= 1: return 2;
default: return 3;
}

What happens if c == 2?
What happens if the guards have side effects?

For that matter:

switch (c) {
case Integer i: return 1;
case Number n: return 2;
case Object o: return 3;
default: return 4;
}

What happens if c is an Integer? A Number? An Object? Is the default
branch actually necessary if one of the branches specifies Object with
no guards?

M
```

More information about the amber-dev mailing list