Switch expression with enum and when clause

Nolwenn Doucet donolwenn at gmail.com
Thu Nov 23 23:11:46 UTC 2023


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