📘

Generic Variance in Kotlin

Jul 13, 2024

Chapter 19: Generic Variance in Kotlin

Key Concepts

  • Generic Variance: Explaining why an array of integers is not a subtype of an array of numbers.
  • Variance in Type Hierarchies: Variance doesn't only apply to generics but also to regular type hierarchies.

Vending Machine Interface Example

  • Type Associations: Example with vendingMachine interface with two types:
    • Parameter type: coin
    • Return type: snack
  • Variance describes the relationship between the container type and its associated types.
    • Vending machine interacting with coin and snack.

Covariance

  • Definition: As the container type becomes more specific, so can the return type.
    • candyBar is a subtype of snack.
    • Demonstrated through SimpleVendingMachine always returning a candyBar which is a subtype of snack.
  • Rule: Return types can become more specific in subtypes (covariance).
  • Error Prevention: Kotlin prevents replacing with a more general type (e.g., product instead of snack).

Contravariance

  • Definition: As the container type becomes more specific, the parameter type can become more general.
    • money type includes more than just coin.
    • Function overloading in Kotlin affects covariance for parameters.
  • Function Overloading Workaround: Change function to a property with a function type to utilize more general parameters.
  • Summary: Return types (covariance) and parameter types (contravariance).

Application to Generics

  • Kotlin Syntax:
    • out: indicates covariant relationship (appears as return type).
    • in: indicates contravariant relationship (appears as parameter type).
  • Generic Interface: vendingMachine converted into a generic interface.
    • Rules for type arguments in generics paralleling type relationships in regular hierarchies.

Final Thoughts

  • Understanding variance in type hierarchies helps clarify generic variance.
  • Encouragement to experiment and code with these concepts.
  • Availability of more detailed content in upcoming Chapter 19 of