235
How It Works
Java 11 introduced the local variable syntax for lambda parameters to align the syntax
of a parameter declaration in an implicitly typed lambda expression with the syntax of a
local variable declaration.
It surely makes our code more readable. For more information
on the var keyword,
see the documentation at
https://openjdk.java.net/jeps/323
.
6-10. Switch Expressions
Problem
You want to efficiently use a switch expression issues without the break.
Solution
Simply you can use a lambda-style syntax for your expressions. So, you can rewrite the
lambda from this form.
switch(input_variable) {
case one:
returnValue = 12
break;
case two:
returnValue = 75
break;
default:
//
code of default block
}
To that form:
int numLetters = switch (input_variable) {
case one -> 12;
case two -> 75;
default -> {// code of default block }
};
ChapTer 6 LaMbda expressIons
236
You can rewrite Recipe 6-4 using lambda-style syntax for switch expression from
switch(status){
case 0:
returnValue = "ACTIVE";
case 1:
returnValue = "INACTIVE";
case 2:
returnValue = "INJURY";
default:
returnValue = "ON_BENCH";
}
to the following form.
returnValue =switch(status){
case 0 -> "ACTIVE";
case 1 -> "INACTIVE";
case 2 -> "INJURY";
default -> "ON_BENCH";
};
The output is the same.
Do'stlaringiz bilan baham: