gpt4 book ai didi

kotlin - Java Lambda类型推断无法按预期在Kotlin中运行

转载 作者:行者123 更新时间:2023-12-02 12:43:55 26 4
gpt4 key购买 nike

如果没有Collectors.toList<String>()中的显式类型参数,为什么这段Java代码无法在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流,请 checkout 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/

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