switch文でのアロー構文
switch文でアロー演算子を用いたコードを初めて見たのでメモとして残しておく。
アロー演算子「->」を使うことでswitch文の「:」と[break;]を省略することができる。
{}でブロックを作れば複数行の処理も書ける。
String str = "B";
switch(str){
case "A" -> System.out.println("A");
case "B" -> System.out.println("B");
case "C" -> {System.out.println("C");
System.out.println("D");
System.out.println("E");
}
}
普通の書き方
String str = "B";
switch(str){
case "A": System.out.println("A");
break;
case "B": System.out.println("B");
break;
case "C": System.out.println("C");
System.out.println("D");
System.out.println("E");
break;
}
何がいいのか
- breakの書き忘れを防止したい場合に有効。
- 見た目もすっきりする。