Kotlingenericstypes参数

在以下源代码

fun main(args: Array) { 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  addInt(item:T, list:MutableList){ list.add(item) } fun  addAnotherInt(item:T, list:MutableList){ list.add(item) } 

函数addIntaddAnotherInt作为参数是一个逆MutableListNumber MutableList 。 但是在main函数中,一行通常编译,另一行不行。

我也检查了从这些函数生成的Java代码,他们似乎是相同的。

addIntaddAnotherInt函数有addInt addAnotherInt

in Number表示“ Number或其超types”。 Int不是“ Number或其超types”,它是它的子types。

简而言之,你声明你的addAnotherInt()一个至少与接受任何types的Number一样的通用列表。

相比之下, addInt声明item: Tlist: MutableListT本身被声明为函数的自由typesvariables ,这意味着它将被绑定在每个特定的调用地点。 所以当你说

 addInt(4, mutableIntList) 

Kotlin基于第一个参数将T绑定到Int ,并将其传播到第二个参数,该参数现在是MutableList 。 你传递了一个与该types兼容的MutableList ,所以Kotlin是满足的。

如果你宣布

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

那么代码将被编译,因为现在列表是一般的,你可以添加任何Number

你的代码将编译一个数字列表:

 val mutableIntList = mutableListOf(1, 2, 3) 

但是由于types被推断为MutableList ,所以不能用它作为MutableList 。 这转换为Java等价的MutableList MutableList并且意味着您可以将任何Number添加到列表中。 但是,将一个Long添加到MutableList是不可能的。

你的第二个方法addInt()是更严格一点,并翻译MutableList MutableList在你的用例。 因此,你可以这样使用它。 两种方法都可以使用MutableList