Pattern Matching for switch (Second Preview)

Tesla Zhang ice1000kotlin at foxmail.com
Thu Sep 23 06:32:41 UTC 2021


I am thinking about the following case:


var e = verylong.expression;
switch (e) {
  default -> println(e.getClass());
  case X x -> doSomething(x);
}


I would like to inline the variable `e`, but that's impossible as we used it twice. However, `e` is only needed in the default case, so what about allowing the following syntax, where we have a pattern in the default branch?


switch (verylong.expression) {
  default e -> println(e.getClass());
  case X x -> doSomething(x);
}



This should be somehow equivalent to an Object type-case:


switch (verylong.expression) {
  case X x -> doSomething(x);
  case Object e -> println(e.getClass());

}


But I like the default syntax since it can be put to the beginning of the switch expression, and the type of `e` may not always be Object.


Regards,


Tesla

---Original---
From: "Remi Forax"<forax at univ-mlv.fr>
Date: Wed, Sep 22, 2021 16:37 PM
To: "jan lahoda"<jan.lahoda at oracle.com>;
Cc: "amber-dev"<amber-dev at openjdk.java.net>;
Subject: Re: Pattern Matching for switch (Second Preview)


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 ->

5. add an partial order edge between a guarded pattern and a constant of a subtypes of the type of the guarded pattern
   This code currently compiles
    switch(value) {
      case Integer i && bar() -> {}
      case 3 -> {}
      case Integer i -> {}
    }

   but i think it should be written
    switch(value) {
      case 3 -> {}
      case Integer i && bar() -> {}
      case Integer i -> {}
    }

   so the code is easier to read. 

Rémi

----- Original Message -----
> From: "jan lahoda" <jan.lahoda at oracle.com>
> To: "amber-dev" <amber-dev at openjdk.java.net>
> Sent: Mercredi 22 Septembre 2021 18:11:13
> Subject: Pattern Matching for switch (Second Preview)

> Hi,
> 
> There is a new draft JEP for preview 2 of Pattern Matching for switch here:
> https://bugs.openjdk.java.net/browse/JDK-8273326
> 
> The exact changes that will be done under this round of preview are yet
> to be determined, but changes related to generics handling in pattern
> matching switches seem to be plausible.
> 
> Feedback is welcome!
> 
> Thanks,
>      Jan


More information about the amber-dev mailing list