5

Is there a way to implement an inline switch statement in java?

Right now, i'm using the following:

    private static String BaseURL = (lifeCycle == LifeCycle.Production)
        ? prodUrl
        : ( (lifeCycle == LifeCycle.Development)
            ? devUrl
            : ( (lifeCycle == LifeCycle.LocalDevelopment)
                  ? localDevUrl
                  : null
            )
        );

I would much prefer it if I could do something like:

    private static String BaseURL = switch (lifeCycle) {
        case Production: return prodUrl;
        case Development: return devUrl;
        case LocalDevelopment: return localDevUrl;
    }

I do know you could achieve this by moving the BaseURL variable into a function GetBaseURL where the switch occurs (see below), however I'm more so just curious if this feature even exists in Java.

static String GetBaseURL() {
    switch(lifeCycle) {
        case Production: return prodUrl;
        case Development: return devUrl;
        case LocalDevelopment: return localDevUrl;
    }

    return null;
} 

I'm transitioning from Swift, and in Swift I know you could do this:

private static var BaseURL:String {
    switch (API.LifeCycle) {
        case .Production:
            return prodUrl
        case .Development:
            return devUrl
        case .LocalDevelopment:
            return localDevUrl
    }
}
1
  • 1
    Does it have to be a switch statement? It would be much cleaner with a Map Commented May 28, 2019 at 0:25

1 Answer 1

10

Assuming LifeCycle is an enum, then you're in luck, as switch expressions were introduced as a preview feature in JDK 12. By using them, your code would look like the following:

LifeCycle lifeCycle = ...;

String baseURL = switch (lifeCycle) {
    case Production -> prodUrl;
    case Development -> devUrl;
    case LocalDevelopment -> localDevUrl;
};

If the LifeCycle enum contains more than those three values, then you'll need to add a default case; otherwise, it will be a compile-time error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.