Is there a way to implement an inline switch statement in java?
Right now, i'm using the following:
private static String BaseURL = (lifeCycle == LifeCycle.Production)
? prodUrl
: ( (lifeCycle == LifeCycle.Development)
? devUrl
: ( (lifeCycle == LifeCycle.LocalDevelopment)
? localDevUrl
: null
)
);
I would much prefer it if I could do something like:
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;
}
I'm transitioning from Swift, and in Swift I know you could do this:
private static var BaseURL:String {
switch (API.LifeCycle) {
case .Production:
return prodUrl
case .Development:
return devUrl
case .LocalDevelopment:
return localDevUrl
}
}
Assuming LifeCycle
is an enum
, then you're in luck, as switch expressions were introduced as a preview feature in JDK 12. By using them, your code would look like the following:
LifeCycle lifeCycle = ...;
String baseURL = switch (lifeCycle) {
case Production -> prodUrl;
case Development -> devUrl;
case LocalDevelopment -> localDevUrl;
};
If the LifeCycle
enum contains more than those three values, then you'll need to add a default
case; otherwise, it will be a compile-time error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With