Kotlin中具有BiPredicate的Files.find() [英] Files.find() with BiPredicate in Kotlin

查看:114
本文介绍了Kotlin中具有BiPredicate的Files.find()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文件树中找到所有文件.在Java中,我会写类似的东西:

I want to find all files in files tree. In Java I'd write something like:

try(Stream<Path< paths = Files.find(startingPath, maxDepth,
   (path, attributes) -> !attributes.isDirectory())) {
          paths.forEach(System.out::println);
}

但是我正在使用kotlin,并想到了:

But I am using kotlin, and came up with this:

Files.find(startingPath,maxDepth,
        { (path, basicFileAttributes) -> !basicFileAttributes.isDirectory()}
).use { println(it) }

但是,这给了我错误:

无法推断此参数的类型.请明确指定.

Cannot infer a type for this parameter. Please specify it explicitly.

类型不匹配:

必填:BiPredicate<路径!,BasicFileAttributes! >!

Required: BiPredicate< Path!, BasicFileAttributes! >!

找到:(???)->布尔值

Found: (???) -> Boolean

您知道在这种情况下如何使用BiPredicate吗?
预先感谢

Any idea how to use BiPredicate in this case?
Thanks in advance

推荐答案

BiPredicate是Java类,Kotlin函数类型不直接兼容.这是由于缺少SAM转换,我最近在此处中也对此进行了解释.

BiPredicate is a Java class, Kotlin function types are not directly compatible. This is due to missing SAM conversions, also explained in my recent answer here.

您需要传递的是类型为BiPredicate<Path, BasicFileAttributes>的对象matcher.澄清一下,像这样:

What you need to pass is an object matcher of type BiPredicate<Path, BasicFileAttributes>. To clarify, something like this:

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甚至能够推断出通用参数类型.因此,总的来说,您的表情将是:

When you pass it to Files.find(), Kotlin is even able to infer the generic parameter types. So in total, your expression would be:

Files.find(startingPath, maxDepth, BiPredicate { path, basicFileAttributes ->
    !basicFileAttributes.isDirectory()
}).use { println(it) }

这篇关于Kotlin中具有BiPredicate的Files.find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆