在方法引用的返回值上调用方法 [英] Call a method on the return value of a method reference
问题描述
我有一个文件流要根据文件名的结尾进行过滤:
I have a stream of files that I want to filter based on the ending of the file name:
public Stream<File> getFiles(String ending) throws IOException {
return Files.walk(this.path)
.filter(Files::isRegularFile)
.map(Path::toFile)
.filter(file -> file.getName().endsWith(ending));
}
虽然最后一行的lambda还不错,但我想我可以用方法也在那里引用,如下所示:
While the lambda in the last line is not bad, I thought I could use method references there as well, like so:
.filter(File::getName.endsWith(ending));
或者用括号括起来。但是,这失败了此表达式的目标类型必须是功能接口
Or alternatively wrapped in parentheses. However, this fails with The target type of this expression must be a functional interface
你能解释为什么这个没有工作?
Can you explain why this doesn't work?
推荐答案
你能解释为什么这不起作用吗?
Can you explain why this doesn't work?
方法引用是lambda表达式的语法糖。例如,方法引用 File :: getName
与(文件 f) - > f.getName()相同
。
Method references are syntactical sugar for a lambda expression. For example, the method reference File::getName
is the same as (File f) -> f.getName()
.
Lambda表达式是用于定义功能接口实现的方法文字,例如 Function
, Predicate
,供应商
等
Lambda expressions are "method literals" for defining the implementation of a functional interface, such as Function
, Predicate
, Supplier
, etc.
为了使编译器知道您正在实现什么接口,lambda或方法引用必须具有目标类型:
For the compiler to know what interface you are implementing, the lambda or method reference must have a target type:
// either assigned to a variable with =
Function<File, String> f = File::getName;
// or assigned to a method parameter by passing as an argument
// (the parameter to 'map' is a Function)
...stream().map(File::getName)...
或(异常)投射到某物:
or (unusually) cast to something:
((Function<File, String>) File::getName)
赋值上下文,方法调用上下文和强制转换上下文都可以为lambda或方法引用提供目标类型。 (在上述所有3种情况中,目标类型为功能<文件, 字符串>
。)
Assignment context, method invocation context, and cast context can all provide target types for lambdas or method references. (In all 3 of the above cases, the target type is Function<File, String>
.)
编译器告诉你的是你的方法引用没有目标类型,所以它不知道如何处理它。
What the compiler is telling you is that your method reference does not have a target type, so it doesn't know what to do with it.
这篇关于在方法引用的返回值上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!