gpt4 book ai didi

java - 在方法引用的返回值上调用方法

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:11 25 4
gpt4 key购买 nike

我有一个文件流,我想根据文件名的结尾过滤:

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 还不错,但我认为我也可以在那里使用方法引用,如下所示:

 .filter(File::getName.endsWith(ending));

或者用括号括起来。但是,这失败了 The target type of this expression must be a functional interface

你能解释一下为什么这不起作用吗?

最佳答案

Can you explain why this doesn't work?

方法引用是 lambda 表达式的语法糖。例如方法引用File::getName(File f) -> f.getName()相同.

Lambda 表达式是用于定义功能接口(interface)实现的“方法文字”,例如 Function , Predicate , Supplier

为了让编译器知道您正在实现什么接口(interface),lambda 或方法引用必须具有目标类型:

// 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)...

或(通常)转换到某物:

((Function<File, String>) File::getName)

赋值上下文、方法调用上下文和强制转换上下文都可以为 lambda 或方法引用提供目标类型。 (在上述所有 3 种情况下,目标类型都是 Function<File, String> 。)

编译器告诉你的是你的方法引用没有目标类型,所以它不知道如何处理它。

关于java - 在方法引用的返回值上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36798635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com