Exhaustiveness and instance patterns

Brian Goetz brian.goetz at oracle.com
Thu Apr 4 17:46:30 UTC 2024


The examples I had worked out previously were all static patterns, so 
this is a good one to work through.

For an instance pattern use, we may or may not put some constraints on 
the receiver expression.  I have an intuition that some sort of 
"effectively constant" constraint is useful, but I haven't fully worked 
through the details.  But that's a separate concern.

In your examples, I think we say that a set of instance patterns { 
x.p1(), x.p2() } are exhaustive if p1 and p2 form a complete set of case 
patterns, _and_ the receiver expressions `x` are provably the same.  I 
think this amounts to "if its a constant or an effectively final 
variable, otherwise you lose."

BTW, it is not just method invocations.  If its a nonfinal field, it 
could be mutated by the p1() implementation (that would be very rude, 
but allowed).



On 4/4/2024 1:29 PM, Tagir Valeev wrote:
> Hello!
>
> Suppose we declare several instance patterns and define that they form 
> an exhaustive set (using syntax from the bikeshed thread):
>
> class X {
>   case pattern(String that) p1() {...}
>   case pattern(String that) p2() {...}
> }
>
> To match, we need an instance of type X. Could it be an arbitrary 
> expression, or it should be a limited thing (e.g., only a local 
> variable)? And how the exhaustiveness will be determined? E.g.:
>
> X myX = ...
> switch(str) {
>   case myX.p1() -> {...}
>   case myX.p2() -> {...}
> }
>
> Here, we can assume that the set of cases is exhaustive, because p1() 
> and p2() have the same effectively-final qualifier. But what if it's a 
> method call?
>
> switch(str) {
>   case getX().p1() -> {...}
>   case getX().p2() -> {...}
> }
>
> The `getX()` method may return different instances of X, and it's not 
> evident anymore whether this set of patterns is exhaustive. Do we have 
> any strategy regarding this case? Or exhaustive sets are not allowed 
> for instance patterns?
>
> With kind regards,
> Tagir Valeev



More information about the amber-spec-experts mailing list