Two new draft pattern matching JEPs
Victor Nazarov
asviraspossible at gmail.com
Thu Mar 4 16:34:15 UTC 2021
Hello Java experts,
I've been following the discussion about new JEPs for pattern matching and
I've observed a controversy considering the introduction of Pattern guards.
It seems that what Brian Goetz stated as a problem is:
> * either we
> don't provide a way to write guarded patterns now (which is not a
> problem for instanceof, but is for switch), or
> * we nail some bit of terrible syntax onto the switch that we're stuck
with.
But from my understanding this misses another route:
> We've already discussed how some patterns (e.g., regex) will take input
> arguments, which are expressions. We haven't quite nailed down our
> syntactic conventions for separating input expressions from output
> bindings, but the notion of a pattern that accepts expressions as input
> is most decidedly not outside the model.
When patterns with arguments become available users are able to write code
like the following (with imaginary syntax).
````
String s = "aabb";
String result = switch (s) {
case String.["(a+)(b+)"]matches(var as, var bs) -> bs + as;
default -> "no match";
}
````
Having this ability nothing prevents users to define a `guard` pattern in
their library and to use it like:
````
case Rectangle(Point x, Point y) & Utils.[x > 0 && y > 0]guard()
````
For me it seems a good solution to introduce a more general mechanism
(patterns with input arguments) and use it to define a library `guard`
pattern then to nail some additional syntax (true/false overload).
So returning to the original problem then I think a possible solution is to
introduce some special `guard` library pattern right away.
Cons:
* Need to decide on special syntax for input arguments right away
* Hard to specify that custom patterns with input arguments are not yet
available and only special library `guard` patterns can use this feature.
Pros:
* Less special syntax in the language, because input arguments are going
to be introduced anyway
* It is probably easier to explain to users the usefulness of `&` because
that way users can already see that not only destructuring pattern are
going to be available, but more generic and complex patterns with input
arguments are going to be available.
--
Victor Nazarov
More information about the amber-spec-comments
mailing list