Intersection types in patterns

Guy Steele guy.steele at oracle.com
Sun Oct 21 03:04:22 UTC 2018



> On Oct 20, 2018, at 12:42 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
> 
>>>    case Point(var x, var y) p: ...
>>> 
>> 
>> Is there a situation where you could have reached that case without
>> having a reference to p? If I've understood so far:
>> 
>> SomeSuperTypeOfPoint q;
>> 
>> switch (q) {
>>   case Point(var x, var y) p: ... // p == q and p : Point
>> }
> 
> Yes, you could have gotten there via
> 
>    switch (getAnObjectForMe()) { 
>        case Point(var x, var y) p: 
>    }
> 
> But, one could always refactor to 
> 
>    Object o = getAnObjectForMe();
>    switch (o) { 
>        case Point(var x, var y) p: 
>    }
> 
> and we’re back to the previous case.  

I believe that @-patterns (I’ll call them that for now) are especially useful in nested situations, where it is not convenient to do that kind of refactoring:

   Object o = getAnObjectForMe();
   switch (o) { 
       case Line(Point(var x1, var y1) p1, Point(var x2, var y2) p2):
		// Now you have your hands on the two points as well as their x and y coordinates
   }

So the question is how much that comes up in practice.

But even without nesting, the original example has the benefit of having verified the type of o and made it available in p with the matched type Point.

This is a very convenient idiom if you want to test x and y in order to decide which method of p to call, for example.

—Guy


More information about the amber-spec-experts mailing list