Nat*_* F. 4 java switch-statement
有没有一种方法可以在Java中实现内联switch语句?
现在,我正在使用以下内容:
private static String BaseURL = (lifeCycle == LifeCycle.Production)
? prodUrl
: ( (lifeCycle == LifeCycle.Development)
? devUrl
: ( (lifeCycle == LifeCycle.LocalDevelopment)
? localDevUrl
: null
)
);
Run Code Online (Sandbox Code Playgroud)
如果可以执行以下操作,我将更喜欢它:
private static String BaseURL = switch (lifeCycle) {
case Production: return prodUrl;
case Development: return devUrl;
case LocalDevelopment: return localDevUrl;
}
Run Code Online (Sandbox Code Playgroud)
我知道您可以通过将
BaseURL变量移动到GetBaseURL发生切换的函数中来实现此目的(请参阅下文),但是我只是很好奇这个功能是否甚至存在于Java中。
static String GetBaseURL() {
switch(lifeCycle) {
case Production: return prodUrl;
case Development: return devUrl;
case LocalDevelopment: return localDevUrl;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我正在从Swift过渡,在Swift中,我知道您可以这样做:
private static var BaseURL:String {
switch (API.LifeCycle) {
case .Production:
return prodUrl
case .Development:
return devUrl
case .LocalDevelopment:
return localDevUrl
}
}
Run Code Online (Sandbox Code Playgroud)
假设LifeCycle是enum,那么您很幸运,因为JDK 12 中将开关表达式作为预览功能引入了。通过使用它们,您的代码将如下所示:
LifeCycle lifeCycle = ...;
String baseURL = switch (lifeCycle) {
case Production -> prodUrl;
case Development -> devUrl;
case LocalDevelopment -> localDevUrl;
};
Run Code Online (Sandbox Code Playgroud)
如果LifeCycle枚举包含三个以上的值,那么您需要添加一个default大小写;否则,将是编译时错误。
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |