https://kotlinlang.org logo
Title
d

diesieben07

06/25/2018, 9:28 AM
And a
MutableList<Object>
is a
MutableList<in CharSequence>
because you can put any
CharSequence
into a list of objects.
p

paulex

06/25/2018, 10:31 AM
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

diesieben07

06/25/2018, 10:38 AM
Apart from the fact that
val
cannot be reassigned: Both are not correct.
p

paulex

06/25/2018, 10:43 AM
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

diesieben07

06/25/2018, 10:45 AM
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

paulex

06/25/2018, 10:54 AM
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

diesieben07

06/25/2018, 10:54 AM
y
is
ViewInterface<in Animal>
, i.e. "i can take animals". But
x
can only take cats, not any animal.
p

paulex

06/25/2018, 12:43 PM
I want to say i big thank you for thanking out time to explain this..