The good and the bad static pattern ?

Brian Goetz brian.goetz at oracle.com
Tue Jan 19 17:05:11 UTC 2021


To put this in context, let's look at what other curly-brace language 
have done.

Scala's pattern matching leans primarily (IMO, way too much) on static 
patterns; most patterns in Scala are static methods called "unapply" 
that takes the target as an ordinary parameter and encoding their 
bindings with some (ad-hoc) combination of optionals, booleans, and 
tuples.  Scala simulates deconstruction patterns with this, as well as 
the use cases we've described for static patterns.  (Scala also has 
"pattern objects", whose unapply methods are instance methods, but this 
isn't exactly like the instance patterns we're proposing here.)

C#'s pattern matching has only deconstruction patterns; you define a 
`Deconstruct` method, which is like our deconstruction patterns.

What's new here is that we are trying to integrate these concepts into 
the object model in an organized and intrinsic way, rather than trimming 
around the edges.  Declared patterns are code that tells us how to take 
a target and conditionally extract the bits we want.  The novel idea 
here is that this really should have been part of the object model all 
along; we have many language features for aggregation, but we leave 
destructuring as an "exercise for the reader."

Remi, is your discomfort about static patterns basically "Well, Scala 
gets away with having only one kind, that subsumes deconstruction and 
static, isn't that good enough?"

On 1/18/2021 3:03 AM, Remi Forax wrote:
> In the last document sent by Brian, there is a notion of static Pattern.
>
> Here is an example of static patterns
>    switch(o) {
>      case String.matcher("(a*)(b*)", matcher -> ...
>      case Integer.parseInt(var value) -> ...
>    }
>
> The first pattern, check if o is an instance of a String that match the regex "(a)(b)" and provides the Matcher to retrieve the matching groups.
> The second pattern, check if o is an instance of a String and can be parsed as an integer and bind that integer to value.
>
> The first pattern correspond to an instance method inside java.lang.String, while the second pattern correspond to a static method inside java.lang.Integer.
>
> One problem is that while it's obvious that the first pattern starts by checking if o is an instanceof String,
> it's far less clear from a user POV that the second pattern does exactly the same thing and does not check if o is an instance of Integer.
>
> So should we support the form of the second pattern, a static Pattern linked to a static method ?
> Or should we restrict ourselves to static patterns that are expressed as instance method ?
>
> regards,
> Rémi
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20210119/d6ac65cd/attachment.htm>


More information about the amber-spec-experts mailing list