i came to this problem in Kotlin I have a mutable list of type Int which is supposedly to be only for writing, however, it allows me to read from it
{
val listOfInt: MutableList<in Int> = mutableListOf<Number>(1.3434, 4.432)
println(listOfInt[0])
1.3434
}
although it wont let me just simply create without specifying only for writing
{
val listOfInt: MutableList<Int> = mutableListOf<Number>(1.3434, 4.432)
}
As for contravariance you are not supposed to be able to get any data from it. It is a bug or a feature?
Thanks
Try this:
The difference is that
println
takes anAny?
Given a
MutableList<in Int>
, the specified type only applies to things you put into it. They have to beInt
or subclasses. It does not apply to things you get out of it, so they areAny?
. All the methods that read things are still there, though.The restrictions you're thinking of show up when you declare a class:
Here the compiler complains, because I say that I want to return a value of the specified type. My request makes no sense, because anyone who tries to use that method would get an
Any?