Last active
October 10, 2021 02:23
-
-
Save nowshad-hasan/92ed74c1db379f02cc88b9abd0061e3b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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