Type Variance

Part 1

Parameter type Contravariance

 

Return type Covariance

Warm-up concepts

Inheritance

Variance

Inheritance

  • parent is broad type
  • child is narrow / specialized type
  • Parent can be substituted by Parent
  • Parent can be substituted by Child
  • Child cannot be substituted by Parent
  • the >= symbol suggests the direction in which the type is getting narrower
  • the >= symbol suggest the direction in which substitution can happen

Variance

  • can Child override the function with the same signature or can it replace the Parent parameter with Child?
  • can Child override the function with and substitute the return type?
  • the term variance answers the questions above and refers to the direction of substitution that is allowed in the overridden method
class Parent {
  function someFunction(Parent $parent): Parent;
}

class Child extends Parent {

}

Parameter type

contravariance

Type Variance - Part 1 (WIP)

By benelori

Type Variance - Part 1 (WIP)

  • 121