1, preface

Lambda An expression is an anonymous function , Some similar to JavaScript Closure in , Pass a function as an argument ,
The code designed with it will be more concise , More flexible . Many mainstream languages , as Java,C#,C++,Python All support Lambda expression .

2,Lambda Expression syntax

lambda The syntax format of the expression is as follows :
(parameters) -> expression perhaps (parameters) ->{ statements; }
among -> yes Lambda New syntax operators in expressions , call Lambda Operator or arrow operator , It will Lambda Expressions are divided into
Left and right parts .

left : appoint Lambda All parameters required by the expression

right : appoint Lambda body , Namely Lambda The function to be performed by the expression

2.1, for instance

* Created using anonymous inner classes Runnable Interface implementation . Runnable r1 = new Runnable(){ @Override public
void run(){ System.out.println(" Anonymous inner class method "); } };
* use Lambda Runnable r2 = () -> System.out.println("Lambda Mode 1 "); perhaps Runnable
r3 = () -> {System.out.println("Lambda Mode 2 ");};
2.2, Syntax format

Format I : No reference , No return value , Simplest .
Runnable r2 = () -> System.out.println("Lambda Format I ");
Format II : One parameter , No return value .
Consumer<String> con = (p) -> System.out.printf(p);
Format III : When a parameter , Parentheses can be omitted
Consumer<String> con = p -> System.out.printf(p);
Format IV : Multiple parameters , There is a return value
Comparator<Integer> com = (x, y) -> { System.out.println(" Multiple parameters , There is a return value "); return
Integer.compare(x,y); };
Format V : When Lambda There is only one code in the body ,return and {} Can be omitted
Comparator<Integer> com2 = (x, y) -> Integer.compare(x,y);
Format VI : Set the data type of the parameter
Comparator<Integer> com = (Integer x,Integer y) -> {
System.out.println(" Multiple parameters , There is a return value "); return Integer.compare(x,y); }; perhaps
Comparator<Integer> com2 = (Integer x,Integer y) -> Integer.compare(x,y);
2.3, Type inference

We will find that format 6 is based on other formats , Plus the corresponding data type , Then why format 1-5 Don't add data types ?

That's it Lambda The compiler does one more step for us in the expression :

Compiler based on program context , The parameter type is inferred in the background ,Lambda The expression parameter type depends on the context , So the compiler helps us infer , Isn't it great !

Have you learned ?
 

Technology