Home >Java >javaTutorial >Why Does Java 8 Comparator Type Inference Fail When Chaining `thenComparing` Methods?

Why Does Java 8 Comparator Type Inference Fail When Chaining `thenComparing` Methods?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 11:19:10290browse

Why Does Java 8 Comparator Type Inference Fail When Chaining `thenComparing` Methods?

Java 8 Comparator Type Inference Confusion

When using Comparator's static methods, type parameters may be omitted in lambda expressions. However, chaining thenComparing methods can lead to compilation errors.

Understanding the Issue

When chaining thenComparing methods, the compiler loses type information about the first lambda parameter (p1). This is because lambda expressions in method receiver positions do not infer context-sensitive types.

For example, in the following call:

Collections.sort(playlist1,

The above is the detailed content of Why Does Java 8 Comparator Type Inference Fail When Chaining `thenComparing` Methods?. 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