首先,值得看一下Consumer< String>实际上是.
From the documentation:
Represents an operation that accepts a single input argument and
returns no result. Unlike most other functional interfaces, Consumer
is expected to operate via side-effects.
所以这是一个接受String并且不返回任何内容的函数.
Consumer p = ""::equals;
编译成功因为equals可以采用String(实际上是任何Object).等于的结果只是被忽略了.*
p = s -> "".equals(s);
这完全相同,但语法不同.编译器知道不添加隐式返回,因为Consumer不应返回值.如果lambda是一个函数< String,Boolean> ;,它将添加一个隐式返回.虽然.
p = s -> true;
这需要一个String(s),但因为true是表达式而不是语句,所以不能以相同的方式忽略结果.编译器必须添加隐式返回,因为表达式本身不能存在.因此,这确实有一个返回:布尔值.因此,它不是消费者.**
p = s -> ("".equals(s));
同样,这是一个表达,而不是一个陈述.暂时忽略lambdas,你会看到System.out.println(“Hello”)行;如果将它包装在括号中,它将同样无法编译.
If the body of a lambda is a statement expression (that is, an expression that would be allowed to stand alone as a statement), it is compatible with a void-producing function type; any result is simply discarded.
A lambda expression is congruent with a [void-producing] function type if … the lambda body is either a statement expression (07004) or a void-compatible block.