I'm trying to initialize two variables with an enhanced switch statement:
int num = //something
boolean val1;
String val2;
val1, val2 = switch(num) {
case 0 -> (true, "zero!");
case 1 -> (true, "one!");
default -> (false, "unknown :/");
}
Is this possible?
Since you are already on Java-13, I would suggest refraining from using an additional library to represent a tuple and make use ofMap.entry
(introduced in Java-9) with the syntactic sugar of local variable type var
inferred.
var entry = switch (num) {
case 0 -> Map.entry(true, "zero!");
case 1 -> Map.entry(true, "one!");
default -> Map.entry(false, "unknown :/");
};
boolean val1 = entry.getKey();
String val2 = entry.getValue();
There’s not necessarily a benefit in cramming the initialization of two variables into one statement. Compare with
var val1 = switch(num) { case 0, 1 -> true; default -> false; };
var val2 = switch(num) { case 0 -> "zero!"; case 1 -> "one!"; default -> "unknown :/"; };
But for completeness, the new switch
syntax does allow assignments too:
boolean val1;
String val2;
switch(num) {
case 0 -> { val1 = true; val2 = "zero!"; }
case 1 -> { val1 = true; val2 = "one!"; }
default -> { val1 = false; val2 = "unknown :/"; }
}
You could also use the expression form to provide the initializer to one variable and assign the other
boolean val1;
String val2 = switch(num) {
case 0 -> { val1 = true; yield "zero!"; }
case 1 -> { val1 = true; yield "one!"; }
default -> { val1 = false; yield "unknown :/"; }
};
but I wouldn’t be surprised if you don’t like it. For this specific example, it would also work to just use
var val2 = switch(num) { case 0 -> "zero!"; case 1 -> "one!"; default -> "unknown :/"; };
var val1 = !val2.equals("unknown :/");
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