CKTIS / Java
Návestia case v switch
Návestia case v switch: Návestie case vyberá vetvu switch podľa konštanty, hodnoty enum, String alebo typového vzoru; Java 21 môže explicitne spracovať aj null.
Verzia: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
caseNávestie case vyberá vetvu switch podľa konštanty, hodnoty enum, String alebo typového vzoru; Java 21 môže explicitne spracovať aj null.
Používaj pravidlá case ... -> bez fall-through, vzory s when na klasifikáciu objektov a vyčerpávajúci switch expression pre uzavretú hierarchiu.
Širší vzor nesmie dominovať neskoršiemu užšiemu, dve návestia nesmú zodpovedať rovnakej konštante a default môže skryť nový nespracovaný prípad.
Tradičný case s dvojbodkou bez break pokračuje ďalej, null vyžaduje explicitný case a switch expression musí byť vyčerpávajúci a na každej ceste dať hodnotu.
Štyri pravidlá case dajú null, negative, integer:7 a text:4 a ukazujú null, strážený vzor, Integer a String.
Príklady
public class Main {
static String classify(Object value){return switch(value){case null->"null";case Integer i when i<0->"negative";case Integer i->"integer:"+i;case String s->"text:"+s.length();default->"other";};}
public static void main(String[] args){System.out.println(classify(null));System.out.println(classify(-2));System.out.println(classify(7));System.out.println(classify("Java"));}
}
Výsledok
null negative integer:7 text:4
Štyri pravidlá case dajú null, negative, integer:7 a text:4 a ukazujú null, strážený vzor, Integer a String.