Syntax Elements
Lambda Operator (->)
Divides the lambda expression into two parts:
Left side: Parameter list.
Right side: Lambda body (actions or return).
Single expression: Directly returns the result of an expression.
Code block: Contains multiple instructions.
Examples of Lambda Expressions:
1) No parameters:
Example: () -> 98.6
Empty parameter list.
Returns a constant value 98.6 (type inferred as double).
Equivalent to method:
double myMeth() {
return 98.6;
}
Example: () -> Math.random() * 100
2) With parameters:
Example: (n) -> 1.0 / n
Returns the reciprocal of n.
Parameter type usually inferred, but may be declared explicitly.
3) Return of Boolean values:
Example: (n) -> (n % 2) == 0
Returns true if n is even, false otherwise.
Simplified form (without parentheses in the parameter):
n -> (n % 2) == 0.
Considerations
The return type of a lambda expression is automatically inferred.
Parentheses in parameters are optional for lambda expressions with a single parameter.
The book suggests using parentheses for consistency in style.
General Summary
The lambda expression simplifies the creation of anonymous methods.
Flexible in terms of parameters and return types.
Adopts a concise syntax to improve code readability and expressiveness.
The above is the detailed content of Fundamentals of lambda expressions. For more information, please follow other related articles on the PHP Chinese website!