Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can there be multiple value assignments for the enhanced switch statement?

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?

like image 743
Allen Liao Avatar asked Feb 12 '20 00:02

Allen Liao


2 Answers

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();
like image 161
Naman Avatar answered Oct 19 '22 11:10

Naman


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 :/");
like image 4
Holger Avatar answered Oct 19 '22 12:10

Holger