假设我们有一个 Predicate
和一个 Function
-Interface:
Function<String, String> function = null;
Predicate<String> predicate = null;
现在我想为 Predicate
-Interface 提供一个方法引用,其中返回类型为 boolean
,在我们的例子中参数为字符串。但为什么下面的方法引用似乎是正确的:
Predicate<String> predicate = String::isEmpty;
isEmpty
-方法没有字符串参数,尽管Predicate
-接口(interface)需要字符串参数。为什么还是对的呢?我错过了什么吗?
另一个例子:在我们的例子中,Function 接口(interface)返回一个 String 并接受一个 String 作为参数。但下面的方法引用似乎是错误的:
Function<String, String> function = String::concat; //wrong
Concat-Method 有一个字符串作为参数并返回一个字符串。为什么是错的?
希望有人能给我解释一下。
最佳答案
当您在实例方法上使用方法引用时,方法接收者将成为第一个参数。所以
String::isEmpty
相当于
(String str) -> str.isEmpty()
和
String::concat
相当于
(String a, String b) -> a.concat(b)
...与函数
的类型不匹配。
关于Java 8 : Do not understand the way Java implements Functional Interfaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42880600/