Towards member patterns
Brian Goetz
brian.goetz at oracle.com
Fri Jan 26 13:33:12 UTC 2024
>
> AN easy example is regular expressions. We have a class
> j.u.regex.Pattern, which represents a compiled regex. A regular
> expression match is a form of pattern match (there's a match
> candidate, it is conditional, if it succeeds we extract the capture
> groups.) Surely we should expose a "match" pattern on Pattern.
>
> class Pattern {
> public __inverse String regexMatch(String... groups) {
> Matcher m = matcher(that);
> if (m.matches())
> __yield IntStream.range(1, m.groupCount())
> .map(Matcher::group)
> .toArray(String[]::new); }
> }
>
> We match it with an explicit receiver:
>
> final Pattern As = Pattern.compile("([aA]*)");
> ...
> if (aString instanceof As.regexMatch(String as)) { ... }
Note that even in the regex-like examples, there is still virtual
dispatch going on, it's just harder to see because j.u.r.Pattern is a
final class. But if it were an interface, with multiple
implementations, then
case As.regexMatch(String as)
would do a virtual dispatch _on the regex implementation_, and then hand
the `String` match candidate to it.
More information about the amber-spec-experts
mailing list