是否可以在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;
}
我确实知道您可以通过将
BaseURL
变量移到发生切换的函数GetBaseURL
中来实现此目的(见下文),但是我更是如此好奇该功能是否甚至存在于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
}
}
答案 0 :(得分:8)
假设LifeCycle
是enum
,那么您很幸运,因为switch expressions是JDK 12中的预览功能。通过使用它们,您的代码看起来像以下:
LifeCycle lifeCycle = ...;
String baseURL = switch (lifeCycle) {
case Production -> prodUrl;
case Development -> devUrl;
case LocalDevelopment -> localDevUrl;
};
如果LifeCycle
枚举包含三个以上的值,则需要添加一个default
大小写;否则,这将是编译时错误。