And a `MutableList<Object>` is a `MutableLis...
# announcements
d
And a
MutableList<Object>
is a
MutableList<in CharSequence>
because you can put any
CharSequence
into a list of objects.
p
Please i'm very Sorry to bother you: MutableList<in Charsequence>... var x:MutableList<Charsequence> var y:MutableList<String> why is this not correct; x = y but y = x is correct
d
Apart from the fact that
val
cannot be reassigned: Both are not correct.
p
Copy code
open class Animal{
    private var id:Int = 0
}

data class Cat(
    private var name:String = ""
):Animal()

interface ViewInterface<in T:Animal> {
    fun setAnimal(animal:T)
}

fun main(args:Array<String>){
    
    var x:ViewInterface<Cat> = object:ViewInterface<Cat>{
        override fun setAnimal(s:Cat){
			println("Cat was set")
        } 
    }

    var y:ViewInterface<Animal> = object:ViewInterface<Animal>{
        override fun setAnimal(s:Animal){
			println("Animal was set")
        } 
    }
        
//     x.setAnimal(Animal())
    
    x = y //*This works*
//     y = x //This doesnt
    
//     x.setAnimal(Animal())
    
}
d
x
is of type
ViewInterface<Cat>
. Since
ViewInterface
uses declaration-site variance, this is really
ViewInterface<in Cat>
and
ViewInterface<Animal>
is assignable to that.
Because if something can take in a
Animal
(your
y
) it can also take in a
Cat
.
ViewInterface<in Cat>
means "anything that can take a Cat". And your
y
fits that, it can even take any animal, which includes cats.
p
but why would
y = x
// fail
y
is animal and i would expect that it to take take a cat
x
however if it was covariant
y = x
is acceptable i know im missing a point buh i'm hoping to get it
d
y
is
ViewInterface<in Animal>
, i.e. "i can take animals". But
x
can only take cats, not any animal.
p
I want to say i big thank you for thanking out time to explain this..