Switch expression with enum and when clause

Remi Forax forax at univ-mlv.fr
Tue Nov 28 14:54:08 UTC 2023


----- Original Message -----
> From: "Brian Goetz" <brian.goetz at oracle.com>
> To: "Nolwenn Doucet" <donolwenn at gmail.com>
> Cc: "amber-dev" <amber-dev at openjdk.org>
> Sent: Monday, November 27, 2023 6:02:01 PM
> Subject: Re: Switch expression with enum and when clause

> Currently, there are two kinds of cases: constant cases and pattern cases.  In
> the long term, we would like to make constant cases go away, and turn these
> into constant patterns — at which point the restriction on guards will be
> lifted.

Also "case null" and "default" can not have a guard too.

regards,
Rémi

> 
>> On Nov 23, 2023, at 6:11 PM, Nolwenn Doucet <donolwenn at gmail.com> wrote:
>> 
>> Hello,
>> 
>> I play with switch expression in java 21 and try to use a when clause on enum
>> values to check
>> a predicate on a class field and sadly it’s not possible.
>> 
>> Will it be possible to do this in a future release or it’s irrelevant use of
>> when clause?
>> 
>> Nolwenn
>> 
>> public class Rental {
>> 
>>   private final Movie movie;
>>   private final int daysRented;
>> 
>>   public Rental(Movie movie, int daysRented) {
>>     this.movie = movie;
>>     this.daysRented = daysRented;
>>   }
>> 
>>   int renterPoints() {
>>    return switch(movie.type()) {
>>       case MovieType.NEW_RELEASE when daysRented > 1 -> 2;
>>       case MovieType.NEW_RELEASE, MovieType.CHILDRENS, MovieType.REGULAR -> 1;
>>     };
>>   }
>> }
>> 
>> public record Movie(String title, MovieType type) {}
>> 
>> public enum MovieType {
>>   CHILDRENS, NEW_RELEASE, REGULAR;
>> }
>> 
>> javac Rental.java
>> Rental.java:22: error: : or -> expected
>>   case MovieType.NEW_RELEASE when daysRented > 1 -> 2;
>>                                      ^
>> Rental.java:22: error: not a statement
>>   case MovieType.NEW_RELEASE when daysRented > 1 -> 2;
>>                                                  ^
>> Rental.java:22: error: ';' expected
> >   case MovieType.NEW_RELEASE when daysRented > 1 -> 2;


More information about the amber-dev mailing list