Advantages of References for Methods
Concision: References to methods are more concise than lambdas.
Example: Increment value in a Map using merge:
Lambda: (count, incr) -> count + incr
Reference for method: Integer::sum
Boilerplate Reduction
Removal of Useless Parameters: Parameters such as count and incr are eliminated.
Example:
map.merge(key, 1, Integer::sum);
Copy after login
Efficient Use of References for Methods
-
Useful Documentation in Lambdas: In some cases, parameter names in lambdas can provide useful documentation.
-
Conversion of Lambdas to Methods: If a lambda is too complex, extract the code into a separate method and use the reference to that method.
IDEs and References for Methods
-
IDE suggestions: IDEs often suggest replacing lambdas with references to methods.
-
Acceptance of Suggestions: Generally, accept suggestions, but evaluate on a case-by-case basis.
Exceptions and Considerations
-
More Concise Lambdas: Sometimes lambdas are more concise than method references.
- Example with Class:
-
Reference for method: GoshThisClassNameIsHumongous::action
-
Lambda: () -> action()
-
Identity Function: Function.identity() vs. x -> x
Types of References for Methods
-
Static: Integer::parseInt (lambda: str -> Integer.parseInt(str))
-
Limited: Instant.now()::isAfter (lambda: t -> Instant.now().isAfter(t))
-
Unlimited: String::toLowerCase (lambda: str -> str.toLowerCase())
-
Class Constructor: TreeMap::new (lambda: () -> new TreeMap)
-
Array Constructor: int[]::new (lambda: len -> new int[len])
Conclusion
Preference for Method References: Use method references when they are shorter and clearer than lambdas.
Use of Lambdas: Prefer lambdas if they are more concise or provide better documentation.

The above is the detailed content of Item Prefer references to methods over lambdas. For more information, please follow other related articles on the PHP Chinese website!