javaswitch-statement

Do nothing in a case of an enhanced switch


I have following enhanced switch case

@Override
public MultivaluedMap<String, String> update(MultivaluedMap<String, String> incomingHeaders,
        MultivaluedMap<String, String> clientOutgoingHeaders) {

    switch (authMethod) {
        case BASIC -> clientOutgoingHeaders.add("Authorization", basicAuth("admin", "admin"));
        case BEARER -> clientOutgoingHeaders.add("Authorization", "Bearer" + " " + getAccessTokenFromKeycloak());
        case SKIP -> System.out.println(); // How can I remove this?
    }
    return clientOutgoingHeaders;
}

where as authMethod is a

enum AuthMethod{
    BASIC,
    BEARER,
    SKIP
}

If authMethodis SKIP I simply want the code to do nothing. I don't want to remove the case.

I am aware, that I could work around this problem in other different ways, but I am curious if this works with an enhanced switch.

Also I am aware, that I could just remove the SKIP case. That is simply not what I want, because I want to make clear, that SKIP does nothing in that case.

This is what I have tried

case SKIP -> {};
case SKIP -> ();

How can I do nothing in a case of an enhanced switch statement?


Solution

  • This is so close!

    case SKIP -> {};
    

    You just had one extra semicolon! Remove it and it compiles!

    case SKIP -> {}
    

    See the syntax for a SwitchRule in the Java Language Specification:

    SwitchStatement:
    switch ( Expression ) SwitchBlock
    
    SwitchBlock:
    { SwitchRule {SwitchRule} } 
    { {SwitchBlockStatementGroup} {SwitchLabel :} }
    
    SwitchRule:
    SwitchLabel -> Expression ; 
    SwitchLabel -> Block 
    SwitchLabel -> ThrowStatement
    

    Notice how, if it is an expression, like your add calls, you need a semicolon after it. If you use a block, like {}, you should not add a semicolon.