Skip to content
Advertisement

How exit from method in a switch expression?

I’m studying switch expression, and I’d like to know how to pass control to the invoker method because “yield” just exits from the switch expression. I can’t find any way to make it behave like the classic switch statement.

Is it even possible?

UPDATE: Here’s a little piece of code.

public static boolean isTimeToParty(DayOfWeek day) {
    boolean isParty = switch (day) {
        case MONDAY -> false;
        case TUESDAY -> {
            yield false; //return not allowed
        }
        case WEDNESDAY -> false;
        case THURSDAY -> false;
        case FRIDAY -> false;
        case SATURDAY -> true;
        case SUNDAY -> true;
    };
    return isParty;
}

What I mean is: How to avoid assigning value to a variable and then calling return [variable_name]? I would like to return value and exit switch at the same time.

Thanks in advance

Advertisement

Answer

As you cannot use return or break within the switch, it would be easier in your case to simplify with return switch ... directly:

public static boolean isTimeToParty(DayOfWeek day) {
    return switch (day) {
        case SATURDAY, SUNDAY -> true;
        default  -> false;
    };
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement