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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3