为什么这段 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/