kotlin - Java lambda 类型推断在 Kotlin 中未按预期工作

标签 kotlin kotlin-interop

为什么这段 Java 代码在 Collectors.toList<String>() 中没有显式类型参数的情况下无法在 Kotlin 中编译?有更惯用的方法吗?

// works
List<String> folders = Files.walk(Paths.get(args[0]))
            .filter(it -> it.toFile().isDirectory())
            .map(it -> it.toAbsolutePath().toString())
            .collect(Collectors.toList());

// does not compile - resulting type is `MutableList<in String!>..List<Any?>?` which is not compatible to `List<String>`
val folders: List<String> = Files.walk(Paths.get(args[0]))
            .filter { it.toFile().isDirectory }
            .map { it.toAbsolutePath().toString() }
            .collect(Collectors.toList())

// compiles
val folders: List<String> = Files.walk(Paths.get(args[0]))
            .filter { it.toFile().isDirectory }
            .map { it.toAbsolutePath().toString() }
            .collect(Collectors.toList<String>())

最佳答案

Why does this piece of Java code not compile in Kotlin without the explicit type parameter in Collectors.toList<String>()?

对我来说这看起来像是一个编译器错误。我建议在 Kotlin (KT) | YouTrack 中创建问题.

Is there a more idiomatic way to do this?

是的。如Kirill Rakhman comments ,“Kotlin 有自己的 File.walk 扩展方法。”例如:

val folders: List<String> = File(args[0]).walk()
        .filter(File::isDirectory)
        .map(File::getAbsolutePath)
        .toList()

如果您更喜欢使用 Java 8 流,请查看 Kotlin/kotlinx.support: Extension and top-level functions to use JDK7/JDK8 features in Kotlin 1.0 。它定义了 Stream<T>.toList()功能:

val folders: List<String> = Files.walk(Paths.get(args[0]))
        .filter { it.toFile().isDirectory }
        .map { it.toAbsolutePath().toString() }
        .toList()

关于kotlin - Java lambda 类型推断在 Kotlin 中未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39075117/

相关文章:

kotlin - 如何使用 KTOR 库配置 ssl?

android - emitAll 直到另一个操作完成?

gradle - IDEA报告build.gradle.kts中ShadowJar任务的错误,而./gradlew运行正常

kotlin - 从 java 中调用作为 java 中关键字的 kotlin 函数?

Kotlin 构造函数委托(delegate)给内部数据类?

kotlin - 为什么在 Kotlin 中调用空值时 toString 不抛出异常?

android - 为什么我在 android 中需要 ViewModelFactory?

kotlin - 在 kotlin 中将监听器对象作为函数参数传递

kotlin - 如何使用 Java 互操作处理可为 null 的泛型

java - 将 vararg 参数传递给 Kotlin 中的另一个函数时出现编译时错误