At the following source code
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)
}
The functions addInt
and addAnotherInt
take as an argument a contravariant MutableList
of Number
. But at the main
function one line compiles normally and the other is not.
I also checked the generated java code from these functions and they seem identical.
What could be the difference between the functions addInt
and addAnotherInt
?