CKTIS / Java
switch — vícecestný výběr
switch — vícecestný výběr: Switch expression vybírá hodnotu z case návěští; arrow rules tvaru case ... -> nepropadají a v Java 21 podporují patterny a guardy when.
Verze: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntaxe
switchSwitch expression vybírá hodnotu z case návěští; arrow rules tvaru case ... -> nepropadají a v Java 21 podporují patterny a guardy when.
Použij Switch expression s arrow rules pro úplné mapování enum či sealed hierarchie; pravidlo s více příkazy vrátí hodnotu přes yield.
Klasická návěští s dvojtečkou mohou bez break propadnout a pořadí patternů podléhá dominanci; default nenahrazuje explicitní case null.
Switch expression musí být úplný; změna binární sealed hierarchie bez rekompilace může vyvolat MatchException a všechny větve určují typ výsledku.
Arrow rules ve Switch expression vyberou hlídaný Integer, pattern String a explicitní case null a dají int:3, text:2 a null.
Příklady
public class Main {
static String describe(Object value) {
return switch (value) {
case null -> "null";
case Integer i when i > 0 -> "int:" + i;
case String s -> "text:" + s.length();
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(describe(3));
System.out.println(describe("hi"));
System.out.println(describe(null));
}
}
Výsledek
int:3 text:2 null
Arrow rules ve Switch expression vyberou hlídaný Integer, pattern String a explicitní case null a dají int:3, text:2 a null.