Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline switch statement java?

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
    }
}
like image 339
Nathan F. Avatar asked Jan 27 '23 06:01

Nathan F.


1 Answers

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.

like image 72
Jacob G. Avatar answered Feb 02 '23 10:02

Jacob G.