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