Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet127/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   123   124   125   126   127   128   129   130   ...   245
Bog'liq
Java 17 Recipes

6-9. Local Variable
 Problem
You want to skip the parameter types and use the var local variable.
 Solution
You can skip the parameter types and rewrite the lambda from this form
(String str1, String str2) -> s1 + s2
to the following form.
(var str1, var str2) -> str1 + str2
You can rewrite Recipe 6-1 using var in the following form.
public static void main(String[] args){
// Create the lambda, passing a parameter named "text" to the
// hello() method, returning the string. The lambda is assigned
// to the helloLambda variable.
HelloType helloLambda =
(var text) -> {System.out.println("Hello " + text);};
// Invoke the method call
helloLambda.hello("Lambda");
}
The following is the output.
Hello Lambda
In this case, the type of the variable text is inferred from context by the compiler, and 
the output is the same. It does not create warnings or errors.
ChapTer 6 LaMbda expressIons


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.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   123   124   125   126   127   128   129   130   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling