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) }
函数addInt
和addAnotherInt
作为参数是一个逆MutableList
的Number
MutableList
。 但是在main
函数中,一行通常编译,另一行不行。
我也检查了从这些函数生成的Java代码,他们似乎是相同的。
addInt
和addAnotherInt
函数有addInt
addAnotherInt
?
in Number
表示“ Number
或其超types”。 Int
不是“ Number
或其超types”,它是它的子types。
简而言之,你声明你的addAnotherInt()
一个至少与接受任何types的Number
一样的通用列表。
相比之下, addInt
声明item: T
和list: MutableList
。 T
本身被声明为函数的自由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 super Number>
MutableList super Number>
并且意味着您可以将任何Number
添加到列表中。 但是,将一个Long
添加到MutableList
是不可能的。
你的第二个方法addInt()
是更严格一点,并翻译MutableList super Int>
MutableList super Int>
在你的用例。 因此,你可以这样使用它。 两种方法都可以使用MutableList
。