java - 内联开关语句java?

标签 java switch-statement

有没有办法在 java 中实现内联 switch 语句?

现在,我正在使用以下内容:

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

如果我能做这样的事情,我会更喜欢它:

    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;
} 

我正在从 Swift 过渡,在 Swift 中我知道你可以这样做:

private static var BaseURL:String {
    switch (API.LifeCycle) {
        case .Production:
            return prodUrl
        case .Development:
            return devUrl
        case .LocalDevelopment:
            return localDevUrl
    }
}

最佳答案

假设 LifeCycle 是一个 enum,那么你很幸运,因为 switch expressions在 JDK 12 中作为预览功能引入。通过使用它们,您的代码将如下所示:

LifeCycle lifeCycle = ...;

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

如果 LifeCycle 枚举包含的值多于这三个值,那么您需要添加一个 default 案例;否则,将是一个编译时错误。

关于java - 内联开关语句java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331373/

相关文章:

java - Storm 发射执行延迟

java - 了解 synchronized 关键字的工作原理

java - apache spark2.3.0以master作为 yarn 启动时,失败并出现错误无法找到或加载主类org.apache.spark.deploy.yarn.ApplicationMaster

java - 如何使用 Google protobuf 通过串行端口进行通信?

excel - 切换功能 Excel

r - 使用 switch 函数代替嵌套 if 函数

Java HttpURLConnection 避免重定向并转到原始页面

c - 在用户不退出的情况下,在 C 中查找两个数字的总和、差等

objective-c - 代替 switch-case,更有效地选择字符串

java - OpenJDK 14.0.1 给出 "the switch expression does not cover all possible input values"