Skip to content

Instantly share code, notes, and snippets.

@nowshad-hasan
Last active October 10, 2021 02:23
Show Gist options
  • Save nowshad-hasan/92ed74c1db379f02cc88b9abd0061e3b to your computer and use it in GitHub Desktop.
Save nowshad-hasan/92ed74c1db379f02cc88b9abd0061e3b to your computer and use it in GitHub Desktop.
private static int getDayExpense2(WeekDay day) {
return switch (day) {
case SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY -> 100;
// case FRIDAY -> 200; // without using 'default', this line creates compile error
// case FRIDAY, SATURDAY -> 200 // valid
default -> 200; // valid
};
}
// We must use 'default' if we have int, String etc. common parameter type.
// Because it can't determine which value is missing, so it expects a general fall-through => default.
private static int getDayExpense3(int indexOfWeek) {
return switch (indexOfWeek) {
case 1, 2, 3, 4, 5 -> 100;
default -> 200;
};
}
// We can also do some extra work inside the case block. When returning value, we've to use 'yield' keyword.
private static int getDayExpense4(WeekDay day) {
return switch (day) {
case SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY -> {
var val = eatLunch();
yield val;
}
case FRIDAY, SATURDAY -> {
yield goToRestaurant();
}
};
}
private static int goToRestaurant() {
return 200;
}
private static int eatLunch() {
return 100;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment