A method reference is a concise Java expression that supplies an existing method or constructor where a functional interface is required. Its brevity can hide which overload is selected or whether the referenced method has the required semantics. section 2.13 section 2.15
Avoid these practical method-reference failures:
- Check the target functional interface before binding an overloaded constructor or method; convert the reference to a lambda when the selected signature is unclear. section 2.13
- Do not infer behavior from a method name alone: Integer::max fits Comparator's types but does not return the sign required for ordering. section 2.14
- Use unit tests and heed static-analysis warnings, while recognizing that compilation alone does not establish correct behavior. section 2.14
A constructor reference that receives an unexpected argument
In contents.computeIfAbsent(fileName, StringBuilder::new), the mapping function receives the missing key. The reference can therefore select StringBuilder(String), producing content beginning with the filename. Use s -> new StringBuilder() when an empty builder is intended. section 2.13
IntBinaryOperator op = Integer::sum; #1 IntBinaryOperator op = (a, b) -> Integer.sum(a, b); #2
Compare a method reference with its equivalent lambda to expose the functional-interface parameters and the target method call. section 2.13
