I couldn’t find this question anywhere else so I figured I might as well ask it. Is it purely aesthetic? Is it faster in any way? What are the main differences between the two? By regular switch, I mean
switch(var){
case 1:
break;
}
and by rule switch, I mean
switch(var){
case 1 -> {}
}
>Solution :
In the regular switch you can omit to break the execution at the end of a code block. This allows a fall-through, and you can handle several different cases with the same code.
switch(var) {
case 1:
dosomething();
break;
case 2:
dosomethindelse();
// the break was forgotten
case 3:
case 4: // these cases shall work on the same code
doanotherthing();
// but the break was forgotten
default:
donothing();
}
This advantage is also a disadvantage since the break can easily be forgotten and then lead to difficult to spot bugs.
Therefore the rule switch was introduced, which – by it’s different syntax does not require a break and thus prevents such situations.