Home  >  Article  >  Java  >  Why Can Method References with Return Types Implement the Consumer Interface in Java?

Why Can Method References with Return Types Implement the Consumer Interface in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-22 10:25:12210browse

Why Can Method References with Return Types Implement the Consumer Interface in Java?

Why Method References with Return Types Match the Consumer Interface

In Java, method references can be used to create functional interfaces. The Consumer interface, for example, takes a single argument and performs an action on it. Surprisingly, method references with return types can also match the Consumer interface.

The decision to allow this behavior was based on the idea of adapting methods to functional interfaces in a similar way to how they are called. Specifically, any value-returning method can be adapted to a Consumer interface, even if the return value is ignored.

Regarding lambda expressions, there are two forms: (args) -> expression and (args) -> { statements* }. The latter form can be void-compatible if no code path attempts to return a value. The former form is value-compatible if the expression evaluates to a value. However, if the expression is also a statement (such as a method invocation or increment/decrement operator), it can be void-compatible.

For instance, the expression s -> s is value-compatible, while s -> i is void-compatible. This is because increment/decrement operators can be used as statements on their own. Another void-compatible expression is s -> new Whatever(s), as class instance creation expressions can also be used as statements.

Interestingly, (arg) -> methodReturningVoid(arg) is the only expression form that is not value-compatible.

The above is the detailed content of Why Can Method References with Return Types Implement the Consumer Interface in Java?. 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