如何将方法 java.util.Collections#copy 转换为 Kotlin?

huangapple go评论84阅读模式
英文:

How method java.util.Collections#copy should look in kotlin?

问题

许多指南试图解释? extend T? super T之间的区别,以java.util.Collections#copy方法作为示例:

public static <T> void copy(List<? super T> dest, List<? extends T> src) {
}

这个方法在 Kotlin 中应该是这样的:

fun <T> copy(dest: List<in T>, src: List<out T>) {
}

然而,当我尝试将此方法复制粘贴到 Kotlin 类中并由 IntelliJ Idea 转换为 Kotlin 时,此方法看起来像这样:

fun <T> copy(dest: List<T?>?, src: List<T?>?) {}

但是这段代码无法编译通过。

英文:

Many guids in which try to explain differences between ? extend T and ? super T use as example method java.util.Collections#copy

public static &lt;T&gt; void copy(List&lt;? super T&gt; dest, List&lt;? extends T&gt; src) {
}

How this method should look in kotlin?
If i try to copy and past this method in Kotlin class and convert to kotlin by IntelliJ Idea when this method look like

fun &lt;T&gt; copy(dest: List&lt;in T?&gt;?, src: List&lt;T?&gt;?) {}

But this code not compiled.

答案1

得分: 0

Kotlin的List是不可变的。参见这个帖子

fun <T> copy(
    dest: MutableList<in T>,
    src: List<T>
) {
}
英文:

Kotlin List are not mutable. See this post

fun &lt;T&gt; copy(
    dest: MutableList&lt;in T&gt;,
    src: List&lt;T&gt;
) {
}

huangapple
  • 本文由 发表于 2020年4月6日 18:06:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/61057322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定