Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading