首页 > 解决方案 > 在 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在这种情况下使用吗?

标签: file-iokotlin

解决方案


BiPredicate是 Java 类,Kotlin 函数类型不直接兼容。这是由于缺少 SAM 转换,在我最近的回答中也有解释

您需要传递的是matchertype的对象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) }

推荐阅读