gpt4 book ai didi

java - 内联开关语句java?

转载 作者:搜寻专家 更新时间:2023-11-01 01:48:50 24 4
gpt4 key购买 nike

有没有办法在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com