Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java 14 switch expression multi-statement support #107

Open
paulirwin opened this issue Feb 14, 2024 · 2 comments
Open

Java 14 switch expression multi-statement support #107

paulirwin opened this issue Feb 14, 2024 · 2 comments

Comments

@paulirwin
Copy link
Owner

With #63, basic support for Java 14 switch expressions was added. There is a multi-statement form of switch expressions that is not yet supported, using the yield keyword to yield the expression from the block of statements.

See: https://docs.oracle.com/en/java/javase/14/language/switch-expressions.html#GUID-BA4F63E3-4823-43C6-A5F3-BAA4A2EF3ADC__GUID-4900EB1C-3832-4CB8-ACAE-A87675260B75

Example:

    Day day = Day.WEDNESDAY;
    int numLetters = switch (day) {
        case MONDAY:
        case FRIDAY:
        case SUNDAY:
            System.out.println(6);
            yield 6;
        case TUESDAY:
            System.out.println(7);
            yield 7;
        case THURSDAY:
        case SATURDAY:
            System.out.println(8);
            yield 8;
        case WEDNESDAY:
            System.out.println(9);
            yield 9;
        default:
            throw new IllegalStateException("Invalid day: " + day);
    };
    System.out.println(numLetters);

We might be able to half-translate this into IIFE-style lambda functions, with a Func<SPECIFY_ME> type where the user must replace SPECIFY_ME with whatever the appropriate type is (which might not be obvious syntactically i.e. if you use var).

This is ugly but it might work in most cases. A warning should be emitted whenever we have to do this. Also note return from the lambda instead of yield.

For example:

    Day day = Day.WEDNESDAY;
    int numLetters = day switch {
        MONDAY or FRIDAY or SUNDAY => ((Func<SPECIFY_ME>)(() => 
        {
            Console.WriteLine(6);
            return 6;
        }))(),
        ...
    };
@OJacot-Descombes
Copy link
Contributor

There is a Proposal: Block-bodied switch expression arms #3037 which will probably be scheduled soon for a C# language design meeting.

@ziaulhasanhamim
Copy link

Switch expressions are incomplete if you can't have multiple lines because you usually need multiple lines. Having blocked-bodied expression arms makes total sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants