sidnt / zionotes

⸮ 🔴zio notes | zio nursery 🔵?
0 stars 0 forks source link

contravariance in function input type #24

Open sidnt opened 3 years ago

sidnt commented 3 years ago

why are functions contravariant in their type parameter
iow, why are input types contravariant

let's say there's a function f1 doSomethingWith(a: Animal)
ie, according to Liskov Substitution Principle
the property provable about it is that it can do something with an animal,
ie, P1 - it can consume values of animal type

let's analyze the function, f2 doSomethingWith(m: Mammal)
given Mammal <: Animal
is P1 provable about f2 as well?
can f2 consume values of Animal type?
No, because, in place of a type, we can't provide values of its supertype.
Mammal type is more constrained than Animal type,
so the usage function f2 might be using some specific property of type Mammal
which might not be available on type Animal

given that LivingBeing >: Animal
let's introduce f0 doSomethingWith(l: LivingBeing)
is P1 provable about f0?
can f0 consume values of type Animal?
Yes. Because in place of a type, we can provide value of its subtype
ie, f0 can honour the constraints of f1
and thus can qualify as f1

hence, the contravariance ...