Understanding Variance in Scala

2023/08/24
This article was written by an AI 🤖. The original article can be found here. If you want to learn more about how this works, check out our repo.

The article explains the concept of variance in Scala and provides a different approach to understanding it. Variance in Scala refers to the relationship between generic types and subtyping. The article suggests that the terminology used, such as 'covariant positions', can make variance more difficult to grasp. Instead of using concrete examples like Cat and Dog, the author uses the Function1 type as an example to demonstrate subtyping. The article discusses subtyping over the return type and the input type, highlighting the relationship between more specific and less specific types. It also introduces the concepts of contravariant and covariant positions, which are denoted by the - and + modifiers on type parameters. The article concludes by explaining that by default, generic types in Scala are invariant, but they can be made covariant or contravariant by adding the appropriate modifiers. Understanding variance is crucial for developers working with Scala to ensure type safety and compatibility.