Home > Java > javaTutorial > Why Does Java 8's `Comparator.reversed()` Cause Type Inference Conflicts with Lambda Expressions?

Why Does Java 8's `Comparator.reversed()` Cause Type Inference Conflicts with Lambda Expressions?

Barbara Streisand
Release: 2024-12-14 20:05:17
Original
732 people have browsed it

Why Does Java 8's `Comparator.reversed()` Cause Type Inference Conflicts with Lambda Expressions?

Type Inference Conflicts Hinder Reversed Lambda Comparators

Despite its widespread use, Java 8's Comparator.reversed() method poses a compilation hurdle when combined with lambda expressions, leading to the following error:

com\java8\collectionapi\CollectionTest.java:35: error: cannot find symbol
            userList.sort(Comparator.comparing(u -> u.getName()).reversed());
                                                     ^
symbol:   method getName()
location: variable u of type Object
1 error
Copy after login

This issue stems from a limitation in the compiler's type inference mechanism. When a lambda expression is used with Comparator.comparing(), it requires a target type to infer the type of the parameter. In the first example, u is determined to be of type User due to the following target type:

Comparator.comparing() -> Function<User, User.getName()> -> User
Copy after login

However, when reversed() is introduced, the target type is disrupted, and the compiler can no longer infer the correct type.

To resolve this issue, one can resort to using method references, which provide additional type information:

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

Alternatively, an explicit parameter type can be specified in the lambda:

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

It remains to be seen whether future compiler enhancements will address this type inference hurdle.

The above is the detailed content of Why Does Java 8's `Comparator.reversed()` Cause Type Inference Conflicts with Lambda Expressions?. 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