Why not pass every method in Java and throw an exception when passing a function type parameter instead of a consumer?

See English answers > Why do consumers accept Lambdas with statement bodies but not expression bodies? 3

This is my code:

Stream.of(1,2,3,4).forEach(a->a.equals(1));//line 1

Stream.of(1,4).forEach(a->{return a.equals(1);});//line 2

Solution

About the working principle of the first line: there is an explanation in the specification:

The above is the following example (a good coincidence, which is very similar to your example):

// Consumer has a void result
java.util.function.Consumer<String> c = s -> list.add(s);

This just means that the compiler will ignore the return type of the expression, as if your code is just like this (valid for void methods):

Stream.of(1,4).forEach(a -> {
     a.equals(1);
});

On the second line, the spec says:

However, in your case, {return a.equals (1);} This rule is not met The void method does not return a value

A simple way to understand this is to consider that the compiler applies method body validation rules (so that the body must be compatible with the declaration public void accept (t t) - as described in tutorial

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>