Home >Java >javaTutorial >Why Does `Comparator.reversed()` Cause Compilation Errors with Java Lambda Expressions?
Compiler Pitfall: Comparator.reversed() and Lambda Expressions
Lambda expressions provide a concise way to customize sorting behavior, but when used with Comparator.reversed(), a compilation error arises. This error stems from the compiler's inability to infer the correct target type for the lambda.
Understanding the Error
Consider the following sample code:
userList.sort(Comparator.comparing(u -> u.getName()).reversed()); // Compiler error
In this case, the error occurs because the compiler cannot determine the type of the parameter u in the lambda expression. To infer the type, the compiler requires a target type for the lambda.
Normally, the target type is established by the context in which the lambda is used. In the first line of the code snippet you provided, the target type is Comparator
Lambda vs. Method Reference
The error only occurs when using a lambda expression. When using a method reference (as in the second line of your code snippet), the target type is explicitly provided by the method signature, resolving the type inference issue.
Resolving the Error
To resolve the error when using a lambda expression, you can explicitly provide the parameter type:
userList.sort(Comparator.comparing((User u) -> u.getName()).reversed());
This explicitly specifies u to be of type User, allowing the compiler to infer the target type correctly.
Compiler Weakness
The error in question highlights a weakness in the compiler's type inference mechanism. The precise reason why the reversed() method disrupts target typing is unclear. Future compiler enhancements may address this issue, allowing lambda expressions to be used without explicit parameter typing.
The above is the detailed content of Why Does `Comparator.reversed()` Cause Compilation Errors with Java Lambda Expressions?. For more information, please follow other related articles on the PHP Chinese website!