file-io - 在 Kotlin 中使用 BiPredicate 的 Files.find()
问题描述
我想在文件树中找到所有文件。在Java中,我会写如下内容:
try(Stream<Path< paths = Files.find(startingPath, maxDepth,
(path, attributes) -> !attributes.isDirectory())) {
paths.forEach(System.out::println);
}
但我正在使用 kotlin,并想出了这个:
Files.find(startingPath,maxDepth,
{ (path, basicFileAttributes) -> !basicFileAttributes.isDirectory()}
).use { println(it) }
但是,这给了我错误:
无法推断此参数的类型。请明确指定。
类型不匹配:
必需:BiPredicate< 路径!,BasicFileAttributes!>!
找到:(???) -> 布尔值
知道如何BiPredicate
在这种情况下使用吗?
解决方案
BiPredicate
是 Java 类,Kotlin 函数类型不直接兼容。这是由于缺少 SAM 转换,在我最近的回答中也有解释。
您需要传递的是matcher
type的对象BiPredicate<Path, BasicFileAttributes>
。为了澄清,这样的事情:
val matcher = object : BiPredicate<Path, BasicFileAttributes>
{
override fun test(path: Path, basicFileAttributes: BasicFileAttributes): Boolean
{
return !basicFileAttributes.isDirectory()
}
}
这可以简化为:
val matcher = BiPredicate<Path, BasicFileAttributes> { path, basicFileAttributes ->
!basicFileAttributes.isDirectory()
}
当你将它传递给 时Files.find()
,Kotlin 甚至能够推断出泛型参数类型。所以总的来说,你的表达是:
Files.find(startingPath, maxDepth, BiPredicate { path, basicFileAttributes ->
!basicFileAttributes.isDirectory()
}).use { println(it) }
推荐阅读
- apache-spark - Spark Master UI 中的应用程序?
- reactjs - Cookies 仅通过 React 代理持久化
- powershell - 运行没有错误且没有结果的 Powershell 脚本
- c++ - 如果使用 goto 将控制权转移到 if(false) 块会发生什么?
- javascript - 为什么执行一个函数后进程没有任何错误就结束了?
- java - 有没有办法在java中获取实例名称?
- dialogflow-es - 在 Dialogflow 中添加条件
- mysql - Python子进程运行mysql转储恢复
- java - 如何使用 maven 从 protobuf 为 Java 目标 11 生成 java 存根?
- quantum-computing - qiskit VQC 带有用于状态准备的幅度编码