[External] : Re: Primitive type patterns
Brian Goetz
brian.goetz at oracle.com
Fri Apr 8 02:54:22 UTC 2022
>
> And, why would we not want duality with:
>
> record R(short s) { }
> ...
> new R(x)
>
>
> because new R(x) is alone while case R(...) is part of a larger set of
> patterns/sub-pattern of the pattern matching, if for each
> pattern/sub-pattern, we need a double-entry table to understand the
> semantics, we are well past our complexity budget.
>
Again: it's the *same table* as all the other conversion contexts. To do
something different here is what would be incremental complexity.
Let me try this one more time, from a third perspective.
What does `instanceof` do? The only reasonable thing you would do after
an `instanceof` is a cast. Asking `instanceof` is asking, if I were to
cast to this type, would I like the outcome? Instanceof currently works
only on reference types, and says no when (a) the cast would fail with
CCE, and (b) if the operand is null, because, even though the cast would
succeed, the next operation likely would not.
Instanceof may be defined only on references now, but casting primitives
is excruciatingly defined with the same full double-entry table that you
don't like.
So, when asking "what does a primitive type pattern mean", then, we can
view this as the generalization of the same question: if I were to cast
this target to this type, would I like the outcome? The set of things
that can go wrong (outcomes we wouldn't like) is slightly broader here;
we can cast a long to int, and we'd get truncation, but that's a bad
outcome, just like CCE. If we interpret `instanceof` as the
precondition test for a useful cast, we again get the same set of
conversions:
- I can safely cast a non-null Integer to int (unboxing with null check)
- I can safely cast any int to Integer (boxing)
- I can safely cast an int in the range of -128..127 to byte
(narrowing with value range check)
- I can safely cast any byte to int (widening)
- etc.
It's a third different explanation, and yet it still comes up with
*exactly the same set of conversions* as the other two explanations
(assignment and method invocation). There's a reason all roads lead
here; because the conversion sets are defined in a consistent manner.
Doing something *different* with pattern matching would be the new
complexity.
More information about the amber-spec-observers
mailing list