Member Patterns -- the bikeshed

Clement Cherlin ccherlin at gmail.com
Thu Apr 4 21:29:35 UTC 2024


 Good summary!

As always, I have strong opinions and suggestions on how to improve just
about everything.

# Use-site syntax

## Deconstruction

if (let MyClassWithDeconstructor(var a, var b) = myThing) { ... }

switch (myThing) {
    case MyClassWithDeconstructor(var a, var b) -> ...
}

## Static

if (MyClass.staticPattern(var a, var b) matches someThing) { ... }

switch (someThing) {
    case MyClass.staticPattern(var a, var b) -> ...
}

## Instance / Bound
If someThing's static type is not MyClass:

if (MyClass.instancePattern(var a, var b) matches someThing) { ... }

switch (something) {
    case MyClass.instancePattern(var a, var b) -> ...
}

Or, if the object's static type is known to be MyClass:

if (myThing.instancePattern(var a, var b)) { ... }

or

if (instancePattern(var a, var b) matches myThing) { ... }

switch (myThing) {
    case instancePattern(var a, var b) -> ...
}

## Unbound

PatternMatcher<MyClass> matcher = MyClass::myPattern;

if (matcher.match(var a, var b) matches someThing) { ... }

switch (someThing) {
    case matcher.match(var a, var b) -> ...
}

# Identifying a member as a pattern

The "pattern" keyword is fine, as long as it's sufficiently contextual to
not break existing usages. For example, `Pattern pattern =
Pattern.compile("...")` should still be a valid field declaration.

# Position of match candidate

None of the above! As previously suggested:

static<A, B> pattern of(A a, B b : Optional<T>)

# Naming of match candidate

I think always using "that" is fine.

# Body types

I agree with the suggested functional, implicit failure, return means fail.

However, I see no need for "match" to take "patternName"[1]. The more
concise `match(BINDINGS)` is preferable to `match patternName(BINDINGS)`.

Indeed, `return` for failure and `return BINDINGS` for success would work
just as well, except in the case of a degenerate pattern with no bindings,
which could `return true` for success and `return` or `return false` for
failure.[2]

# Exhaustiveness

The `case` modifier is fine, but the design should leave room for `case
LABEL` or `case (LABEL1, LABEL2)` to delineate membership in exhaustive
set(s), as a potential future enhancement.

[1] Java already has enough gratuitous repetition in class declarations.

[2] Sorry, Brian, but member patterns *are* basically "conditional
var-return methods". The more the design leans into that, the better. In my
opinion, of course.

# Bonus Gratuitous Perl Advocacy
Alternative spelling suggestion for `a matches b`: `a =~ b`
Alternative spelling suggestion for `!(a matches b)`: `a !~ b`

Cheers,
Clement Cherlin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-spec-observers/attachments/20240404/8f12d539/attachment.htm>


More information about the amber-spec-observers mailing list