Ant*_*arf 4 switch-statement switch-expression java-17
我不明白为什么第一个片段编译得很好:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
但不是这个:
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");
};
Run Code Online (Sandbox Code Playgroud)
对我来说看起来是一样的。
你的第一个变体是一个声明。第二个是用作switch表达式,因此,您可以return从案例中 \xe2\x80\x99t 但必须yield一个值(除非抛出异常)。
var res = switch(s) {\n case Rectangle r: yield 2 * r.largeur() + 2 * r.longueur();\n case Circle c: yield 2 * c.radius();\n default: throw new RuntimeException("not a shape");\n};\n\nRun Code Online (Sandbox Code Playgroud)\n但使用新语法更有意义:
\nvar res = switch(s) {\n case Rectangle r -> 2 * r.largeur() + 2 * r.longueur();\n case Circle c -> 2 * c.radius();\n default -> throw new RuntimeException("not a shape");\n};\nRun Code Online (Sandbox Code Playgroud)\n