Why does a Java method reference with return type match the Consumer interface?

后端 未结 2 1433
死守一世寂寞
死守一世寂寞 2020-11-22 14:36

I am confused by the following code

class LambdaTest {
    public static void main(String[] args) {
        Consumer         lambda1 = s ->          


        
2条回答
  •  深忆病人
    2020-11-22 14:55

    consume(String) method matches Consumer interface, because it consumes a String - the fact that it returns a value is irrelevant, as - in this case - it is simply ignored. (Because the Consumer interface does not expect any return value at all).

    It must have been a design choice and basically a utility: imagine how many methods would have to be refactored or duplicated to match needs of functional interfaces like Consumer or even the very common Runnable. (Note that you can pass any method that consumes no parameters as a Runnable to an Executor, for example.)

    Even methods like java.util.List#add(Object) return a value: boolean. Being unable to pass such method references just because that they return something (that is mostly irrelevant in many cases) would be rather annoying.

提交回复
热议问题