gpt4 book ai didi

generics - Kotlin 泛型类型参数

转载 作者:IT老高 更新时间:2023-10-28 13:44:14 26 4
gpt4 key购买 nike

源码如下

fun main(args: Array<String>) {
println("Hello, world!")

val mutableIntList = mutableListOf(1, 2, 3)

addInt(4, mutableIntList) // No compile-time error
addAnotherInt(5, mutableIntList) // Compile-time error

println(mutableIntList)

}

fun <T: Number> addInt(item:T,
list:MutableList<in T>){
list.add(item)
}

fun <T: Number> addAnotherInt(item:T,
list:MutableList<in Number>){
list.add(item)
}

addIntaddAnotherInt 函数将 Number 的逆变 MutableList 作为参数。但是在 main 函数中,一行编译正常,另一行编译不正常。

我还检查了这些函数生成的 java 代码,它们看起来是一样的。

addIntaddAnotherInt 函数之间有什么区别?

最佳答案

in Number表示“Number 或其父类(super class)型”。 Int不是“Number 或其父类(super class)型”,而是它的子类型。

简单地说,您声明您的 addAnotherInt()想要一个至少与接受任何类型的 Number 一样通用的列表.

相比之下,addInt声明 item: Tlist: MutableList<in T> . T它本身被声明为函数的自由类型变量,这意味着它将被绑定(bind)到每个特定的调用站点。所以当你说

addInt(4, mutableIntList)

Kotlin 绑定(bind) TInt基于第一个参数并将其传播到第二个参数,现在是 MutableList<in Int> .您传入了 MutableList<Int>和那个类型兼容,所以 Kotlin 就满足了。

如果你声明了

val mutableIntList: MutableList<Number> = mutableListOf(1, 2, 3)

然后代码将被编译,因为现在列表已按要求通用,您可以添加任何 Number给它。

关于generics - Kotlin 泛型类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48580508/

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