Skip to content

Instantly share code, notes, and snippets.

@lekeCoder
Created April 28, 2022 21:50
Show Gist options
  • Save lekeCoder/61d5dea1b60c67860a0a1a477da9da85 to your computer and use it in GitHub Desktop.
Save lekeCoder/61d5dea1b60c67860a0a1a477da9da85 to your computer and use it in GitHub Desktop.
Switch vs When example 3
// execute all label expression that is valid
int day = 3;
switch(day){
case 1:
case 2:
case 3:
System.out.println("Wednesday is workday");
case 4:
case 5:
System.out.println("Work day");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
}
// prints "Wednesday is workday"
// "Work day"
// execute the first label expression that is valid
// prints different result depending on order
val day = 3;
when (day) {
1, 2, 3, 4, 5 -> println("Work day")
3 -> println("Wednesday is workday")
6, 7 -> println("Weekend");
}
//outputs: Work day
// lets change the order of the labels
when (day) {
3 -> println("Wednesday is workday")
1, 2, 3, 4, 5 -> println("Work day")
6, 7 -> println("Weekend");
}
//outputs: Wednesday is workday
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment