编辑 2016 年 3 月 1 日:公平警告:此问题是在 1.0.0 之前针对 Kotlin 提出的。自 Kotlin 1.0.0 以来情况有所不同。请参阅下面 @Jayson Minard 的文章,了解 Kotlin 1.0.0 的答案。
在使用 Stream 的 Java 8 代码中,我编写类似的内容
public static void main(String... args) {
Stream<Integer> integerStream = Stream.of(1,2,3);
List<Integer> integerList = integerStream.collect(Collectors.toList());
}
但是在用 Kotlin 编写的类似代码中,我得到了意想不到的结果。
public fun main(args: Array<String>) {
val integerStream : Stream<Int> = Stream.of(1, 2, 3)
// this is what I expect to write, like the Java 8 code, but is a compilation error:
// "required: java.util.List<in kotlin.Int> found: kotlin.MutableList<in kotlin.Int!"
// val list : java.util.List<in Int> = integerStream.collect(Collectors.toList())
// I must instead write this
val list : MutableList<in Int> = integerStream.collect(Collectors.toList())
}
为什么 Kotlin 代码中的 Stream#collect 表达式的返回值的列表类型与 Java 代码中的不同? (我猜这是因为 Kotlin 中一些特定于 Java Collections 的魔法)
最佳答案
我认为这是因为 Java 中的 List
默认情况下是可变的,而在 Kotlin 中它们是不可变的。
在代码中,您使用的是 Java 特定实用程序 Collectors.toList
,它返回一个 Java List
,而 Kotlin 会将其转换为 MutableList
,因此实际上,您正在编写相同的代码,只是类型名称不同。
关于java - 等效 Java 和 Kotlin Stream 代码之间的意外类型差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33715270/