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
Barbara StreisandOriginal
2024-12-14 20:05:17734browse

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

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

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());

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

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

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!

Statement:
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