Java 8:不了解Java实现功能接口的方式 [英] Java 8: Do not understand the way Java implements Functional Interfaces

查看:62
本文介绍了Java 8:不了解Java实现功能接口的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说一个谓词和一个 Function -接口:

lets say we a Predicate and a Function-Interface:

Function<String, String> function = null;
Predicate<String> predicate = null;

现在,我想给 Predicate -Interface一个方法引用,其中返回类型为 boolean ,在我们的示例中为参数字符串.但是,为什么以下方法参考似乎正确:

Now I want to give the Predicate-Interface a method reference where the return type is a boolean and in our case the parameter a string. But why the following method reference seems to be right:

Predicate<String> predicate = String::isEmpty;

isEmpty 方法没有String-Parameter,尽管 Predicate -Interface需要String-Parameter.为什么它仍然正确?我想念什么吗?

The isEmpty-method has no String-Parameter,although the Predicate-Interface requires a String-Parameter. Why it is still right? Am I missing something?

另一个例子:在我们的例子中,Function接口返回一个String并将String作为参数.但是以下方法参考似乎是错误的:

Another Example: The Function interface returns in our case a String and takes a String as parameter. But the following method reference seems to be wrong:

Function<String, String> function = String::concat;  //wrong

Concat方法具有一个字符串作为参数并返回一个字符串.为什么错了?

The Concat-Method has a String as Parameter and returns a String. Why its wrong?

希望有人可以向我解释.

Hopefully somebody can explain it to me.

推荐答案

在实例方法上使用方法引用时,方法接收者将成为第一个参数.所以

When you use a method reference on an instance method, the method receiver becomes the first argument. So

String::isEmpty

等同于

(String str) -> str.isEmpty()

String::concat

等同于

(String a, String b) -> a.concat(b)

...与 Function 的类型不匹配.

...which does not match the type of Function.

这篇关于Java 8:不了解Java实现功能接口的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆