Switch expression with enum and when clause

Brian Goetz brian.goetz at oracle.com
Mon Nov 27 17:02:01 UTC 2023


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.  

> 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