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.
Your first variant is a statement. The second is using
switchas an expression, hence, you can’treturnfrom the cases but have toyielda value (unless throwing an exception).but it makes more sense to use the new syntax: