[External] : Re: Reviewing feedback on patterns in switch
Brian Goetz
brian.goetz at oracle.com
Wed Feb 16 14:48:14 UTC 2022
> Not sure it's a no-brainer.
> The question is more a question of consistency. There are two
> consistencies and we have to choose one, either switch never allows
> null by default and users have to opt-in with case null or we want
> patterns to behave the same way if they are declared at top-level or
> if they are nested. I would say that the semantics you propose is more
> like the current Java and the other semantics is more like the Java of
> a future (if we choose the second option).
You are right that any justification involving "for consistency" is
mostly a self-justification. But here's where I think this is a cleaner
decomposition.
We define the semantics of the patterns in a vacuum; matching is a
three-place predicate involving a static target type, a target
expression, and a pattern. Null is not special here. (This is how
we've done this all along.)
Pattern contexts (instanceof, switch, and in the future, nested
patterns, let/bind, catch, etc) on the other hand, may have pre-existing
(and in some cases reasonable) opinions about null. What's new here is
to fully separate the construct opinions about special values from the
pattern semantics -- the construct makes its decision about the special
values, before consulting the pattern.
This lets instanceof treat null as valid but say "null is not an
instance of anything", past-switch treats null as always an error, and
future-switch treats null as a value you can opt into matching with the
`null` label. (Yes, this is clunky; if we had non-nullable type
patterns, we'd get there more directly.)
But the part that I think is more or less obvious-in-hindsight is that
the switch opinions are switches opinions, and the pattern opinions are
pattern opinions, and there is a well-defined order in which those
opinions are acted on -- the construct mediates between the target and
the patterns. That is, we compose the result from the construct
semantics and-then the pattern semantics.
None of this is really all that much about "how do people like it". But
what I do think people will like is that they get a simple rule out of
switches: "switches throw on null unless the letters n-u-l-l appear in
the switch body". And a simple rule for instanceof: "instanceof never
evaluates to true on null". And that these rules are *independent of
patterns*. So switch and instanceof can be understood separately from
patterns.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20220216/8b02c720/attachment.htm>
More information about the amber-spec-experts
mailing list