Home > Java > javaTutorial > Why Does `Comparator.reversed()` Cause Compilation Errors with Some Lambda Expressions in Java?

Why Does `Comparator.reversed()` Cause Compilation Errors with Some Lambda Expressions in Java?

Mary-Kate Olsen
Release: 2024-12-03 14:51:14
Original
409 people have browsed it

Why Does `Comparator.reversed()` Cause Compilation Errors with Some Lambda Expressions in Java?

Comparator.reversed() Incompatibility with Lambda Expressions

When attempting to sort a list using lambda expressions and the reversed() method of Comparator, a compilation error arises. To understand this behavior, it's crucial to delve into the intricacies of the compiler's type inference mechanism.

Java compiler determines the type of variables in lambda expressions based on the context in which they are used. In this case, the sort method expects an argument of type Comparator. When using method references, the receiver type is already known, and the lambda argument is inferred accordingly. For example:

userList.sort(Comparator.comparing(User::getName).reversed()); // works
Copy after login

However, when using lambda expressions directly, the compiler struggles to infer the type of the variable within the lambda. The target type for the lambda is Comparator, which requires a Function that takes a User as an argument. In the following code, the lambda correctly infers u as a User:

userList.sort(Comparator.comparing(u -> u.getName()).reversed()); // works
Copy after login

However, in the absence of method references, the compiler defaults to inferring the type of u as Object, resulting in the compilation error:

userList.sort(Comparator.comparing(u -> u.getName()).reversed()); // Compiler error
Copy after login

To resolve this issue, one can either use method references if possible or explicitly specify the parameter type within the lambda expression:

userList.sort(Comparator.comparing((User u) -> u.getName()).reversed()); // works
Copy after login

While this limitation can be frustrating, it's a consequence of the compiler's type inference mechanism. Future compiler enhancements may address this issue.

The above is the detailed content of Why Does `Comparator.reversed()` Cause Compilation Errors with Some Lambda Expressions in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template