Search code examples
switch-statementjava-17switch-expression

Java 17 : switch expressions and statements


I don't understand why the first snippet compiles fine :

var res = getResult(s);

public static double getResult(Shape s)  {
        switch(s) {
            case Rectangle r : return 2* r.largeur() + 2* r.longueur();
            case Circle c : return  2*c.radius();
            default : throw new RuntimeException("not a shape");
        }
}

But not this one :

var res = switch(s) {
            case Rectangle r : return 2* r.largeur() + 2* r.longueur();
            case Circle c : return  2*c.radius();
            default : throw new RuntimeException("not a shape");
        };

It looks the same for me.


Solution

  • Your first variant is a statement. The second is using switch as an expression, hence, you can’t return from the cases but have to yield a value (unless throwing an exception).

    var res = switch(s) {
        case Rectangle r: yield 2 * r.largeur() + 2 * r.longueur();
        case Circle c: yield 2 * c.radius();
        default: throw new RuntimeException("not a shape");
    };
    
    

    but it makes more sense to use the new syntax:

    var res = switch(s) {
        case Rectangle r -> 2 * r.largeur() + 2 * r.longueur();
        case Circle c -> 2 * c.radius();
        default -> throw new RuntimeException("not a shape");
    };