gpt4 book ai didi

kotlin - Kotlin 泛型中列表和可变列表的区别

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

我最近研究了 kotlin 泛型,但我发现了一些奇怪的情况
IDE image

interface MyItem

fun <ITEM : MyItem> bindItem(items: List<ITEM>?) {
val castedItem = items as List<MyItem>?
}

fun <ITEM : MyItem> bindItem2(items: MutableList<ITEM>?) {
val castedItem = items as MutableList<MyItem>?
}
仅在 MutableList 情况下,编译器会警告未选中的 Cast
如果有人知道这种情况,请告诉我。

最佳答案

List接口(interface)具有声明站点协方差(<out T>)。这意味着“向上转换”类型是安全的,因为 List 只输出项目。例如,如果您有 List<Int> , 将其用作 List<Number> 是安全的因为 Int始终可以安全地转换为 Number .当您从列表中检索项目时,它们总是满足类型 Int或父类(super class)型 Number .MutableList没有协变类型。它在声明站点是不变的。这意味着“向上转换”它的类型本质上是不安全的。例如,如果您转换 MutableList<Int>MutableList<Number> ,使用 MutableList<Number> 是不安全的引用,因为它可以让您添加 Float到列表中。当原始引用用作 MutableList<Int>并尝试从中检索一个值,它会因为尝试使用 Float 而得到 ClassCastException。作为 Int .
在这种情况下,您可以安全地使用 MutableList到协变类型,如下所示:

val castedItem = items as MutableList<out MyItem>?
但是一个 MutableList协变类型与 List 并没有什么不同。 ,因此最好将其转换为 List<MyItem>使意图更清晰。

关于kotlin - Kotlin 泛型中列表和可变列表的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63157091/

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