Hey, I've a quick-ish question regarding variance....
# announcements
s
Hey, I've a quick-ish question regarding variance. Im having issues wrapping my head around how function parameters are contravariant. Specifically, this excerpt from wikipedia
both functions of type Cat -> Cat and Animal -> Animal can be used wherever a Cat -> Animal was expected.
. Ik its not strictly kotlin related, but kotlin does have the in-out keywords.
r
think of a box and let's say your method accepts boxes of certain sizes. If a sub class accepts even bigger boxes then you are all fine (that's contravariance). You can replace your class with the sub-class and the code still compile. If your sub class expects only smaller boxes (covariance) then you could not use the sub class where you use the class now. So the box could be
Number
bigger box =
Any
smaller box =
Int
(as an example) Or taking your animal example box = cat bigger box = animal smaller box = siamese cat
s
the part that confuses me is how a value of type Animal can be passed as a parameter to a function that accepts a type Cat as in the quote given. What if the function references Cat specific properties that dont exist on type Animal?
r
you cannot pass an animal where a cat is expected
co- and contravariance tells you something about how an overriding method can behave
s
hold up, i think i might actually get the wikipedia quote now. i think i was looking at it from the wrong level. Need to mull this over now until it makes sense 😁 cheers
r
no worries