2

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.

AntonBoarf
  • 1,239
  • 15
  • 31

1 Answers1

6

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");
};
Holger
  • 285,553
  • 42
  • 434
  • 765