each方法不会引发异常

each方法不会引发异常

本文介绍了当传递函数类型参数而不是Consumer时,为什么Java中的for-each方法不会引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不 forEach 方法不会显示编译器错误?这两行都为流中的每个元素都返回一个布尔值,但是只有第二行会出现编译错误?在这种情况下, lambda表达式是否还有其他属性?

Why doesn't forEach method in java not show a compiler error when a Function type argument is passed instead of Consumer? Here both of the lines are returning a boolean value for every element in the stream but only 2nd line gets a compilation error? Is there any other property of lambda expression for such scenario?

这是我的代码:

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

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

推荐答案

关于第一行起作用的原因:规范:

上面带有以下示例(巧合,与您的示例非常相似):

The above comes with the following example (good coincidence, this is very similar to your example):

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

这只是意味着编译器将忽略表达式的返回类型,就像您的代码就是这个(对于void方法有效)一样:

This simply means that the compiler ignores the return type for the expression, as though your code were simply this (which is valid for a void method):

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


关于第二行,规范说:

但是,对于您来说,{return a.equals(1);}不符合此规则.无效方法不会返回值.

In your case, though, {return a.equals(1);} does not meet this rule. Void methods don't return a value.

一种简单的理解方法是考虑编译器应用方法主体验证规则(这样主体必须与声明public void accept(T t)兼容)-如教程

An easy way to understand this is to consider that the compiler applies method body validation rules (such that the body must be compatible with the declaration public void accept(T t)) - as mentioned in the tutorial

这篇关于当传递函数类型参数而不是Consumer时,为什么Java中的for-each方法不会引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 20:26