Pattern Matching for instanceof (Preview 2)
Brian Goetz
brian.goetz at oracle.com
Tue Feb 18 15:14:57 UTC 2020
>> I don’t know what you mean here. There are two patterns, a type test pattern and
>> a deconstruction pattern. In v2 we propose to support deconstruction patterns
>> over record types *only*. A deconstruction pattern looks like this: Point(var
>> a, var b), i.e. all the components are either (recursively) deconstruction
>> patterns, or `var` <identifier>, i.e. with no type needed. I added a note to
>> the JEP page pointing out that this is a starting point, and eventually we will
>> support other patterns in the argument position, specifically <type>
>> <identifier>; hopefully in this release.
> Currently we don't support mixing var and non var in lambda parameters.
> So my question is: does this pattern Point(var x, int y) that mix a 'var' and an explicit type allowed or not ?
Unequivocal "yes". There is a universe of patterns. Some might be
disallowed in certain contexts (e.g., `instanceof var x` seems kind of
silly), but once we decide on the set of patterns allowable in which
contexts, any pattern can be nested inside a deconstruction pattern.
The `var x` pattern can equally be thought of as inference for a total
type pattern, or an "any" pattern; they are semantically equivalent.
If you're asking "but why can I not mix them in a lambda", the answer
is: because we don't support partial inference in lambdas at this time.
We could, and we might someday. (If you're suggesting that the
consistency between the two superficially-related forms is the most
important consideration here, I would disagree.)
>
>> Absolutely not! Note this does mean that you can write confusing code:
>>
>> record Point(int x, int y) { }
>>
>> if (o instanceof Point(var y, var x)) {
>> … // y refers to x component, y refers to x component
>> }
>>
>> (I’ll get my coat…)
> yes, that's why i ask, it leads to very confusing code, some languages don't allow this kind of code,
> by example destructuring in JavaScript as a special syntax if you want to use different names.
>
Preventing this kind of confusing code (which is just a special case of
"picking stupid names") is much more of a job for IDEs than language
specifications.
More information about the amber-spec-observers
mailing list