Inline switch statement java?

Nathan F. :

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
    }
}
Jacob G. :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74678&siteId=1