Pattern Matching for switch (Second Preview)

forax at univ-mlv.fr forax at univ-mlv.fr
Thu Oct 14 09:46:54 UTC 2021


----- Original Message -----
> From: "Gavin Bierman" <gavin.bierman at oracle.com>
> To: "Remi Forax" <forax at univ-mlv.fr>
> Cc: "amber-dev" <amber-dev at openjdk.java.net>
> Sent: Jeudi 14 Octobre 2021 11:19:44
> Subject: Re: Pattern Matching for switch (Second Preview)

> Hi Remi,
> 
> Just circling back to this suggestion of yours:
> 
>> On 22 Sep 2021, at 21:37, Remi Forax <forax at univ-mlv.fr> wrote:
>> 
>> And i think we should also fix the following
>> 
>> 4. a case that mix constants and a type pattern (or a guard) of a supertype of
>> the types of the constants should be allowed
>>   By example,
>>     case 3, Integer i ->
>>   or
>>     case 4, Object o ->
> 
> I’m not really convinced this carries its own weight. Both examples are a little
> odd as the type pattern subsumes the constant, so they don’t really offer much
> in terms of expressiveness. I tried following this train of thought and fiddled
> around with new ways of writing enum constant labels, but still the benefits
> seems modest at best, at least to me.

Yes, it's more a comfort in term of reading because you can always remove the constant and only keep the type pattern.
Here is an example using an AST tree.

sealed interface Expr permits ... {}
sealed interface Lit permits ... extends Expr {}
enum Bool implements Lit { TRUE, FALSE }

switch(expr) {
  // some Expr
  case Bool.TRUE -> ...
  case Bool.FALSE, Lit lit -> ...
  // other Expr
}

which is i believe more readable than

switch(expr) {
  // some Expr
  case Bool.TRUE -> ...
  case Lit lit -> ...
  // other Expr
}


but you're right that it may not worth the trouble.

> 
> I think my main concern about this train of thought is that it is really
> tinkering at the level of switch labels. (I know we did something for null, but
> null is very special/annoying.) I believe it will be more profitable for us to
> consider better *patterns* in this area. For example, (nested) constant
> patterns - e.g. Point(=0, var y) - range patterns - e.g. Point(0..42, var y)
> etc.

=0 is quite weird but i see why you do not want to use ==0 like in C#

> 
> Thanks,
> Gavin

Rémi


More information about the amber-dev mailing list