Sayon Sivakumaran
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Scala: Variance, Covariance, and Contravariance ### Introduction This lesson will explain the different types of variance relations. Given a generic type `G[T]`, where `T` is the type parameter, and given a type `B` and its subtype `A`, variance describes the relation between `G[A]` and `G[B]`. If there is no relation between between `G[A]` and `G[B]`, then `T` is invariant. If `G[A]` is a subtype of`G[B]`, then `T` is covariant. If `G[A]` is a supertype of`G[B]`, then `T` is contravariant. Notice, the type of variance is a property of the type parameter and not the generic classes themselves. The concepts of variance, covariance, and contravariance belong to type theory and thus serveral languages support these concepts. However, for this report, variance relations will be studied through the perspective of Scala. ### Scala Overview [comment]: # (Discuss types and classes, as well as the difference between the two. When referring to Complex types and Component types, use the definitions in the notes. I think it'd make sense to include Generics in Scala as a brief introduction) Scala is a strong, statically typed language that supports object-oriented programming, functional programming, and is often run on a Java Virtual Machine (JVM). Scala was designed to be concise, and many of its design decisions were made to address criticisms of Java. Some of these features include functional programming features such as currying and pattern matching, as well as non-functional programming features like operator overloading and optional parameters. A pre-requsite for understanding variance is understanding generics, which are classes or traits (Scala's more flexible version of Java's interface) that take in a type parameter. The following of are examples of generics: ```scala class ClassGeneric[C] class MultiParamClassGeneric[A,B,C] trait TraitGeneric[T] ``` There are also built-in generics: ```scala val listGeneric1 : List[Int] = null val listGeneric2 : List[Any] = List(1, 9.2, "A") ``` [comment]: # (Regarding code snippets, since we need two for each, I think it would make sense to give one example and one counter-example for each) ### Variance [comment]: # (Review this section after we figure out the difference between types and classes) Variance refers to the way that subtyping relationships of generic types (also called complex types) and their parameter types (also called component types) relate. In essence, it describes the correlation between the inheritance relationships of a generic class and its derived classes, and the inheritance relationships of its parameter class and its derived classes. The existence of variance in Scala allows for developers to have additional information about the subtyping relationship of parameter types, and make abstractions on generic types with hierarchically related parameters. There are three types of variance relationships in Scala, covariance, contravariance, and invariance. ### Covariance For some parameter type `T`, a generic class is made covariant using the annotation `+T`. For some generic class, making its parameter type covariant implies that for two types `A`, `B`, if `B` is a subtype of `A`, then the generic class with parameter `B` is a subtype of the generic class with parameter `A`. We will consider the following example. ```scala class Food(val name: String) class Vegetable(override val name: String) extends Food(name) class GreenVeggie(override val name: String) extends Vegetable(name) ``` In this example, `Food` is a class such that `Vegetable` is a child class of `Food`, and `GreenVeggie` is a child class of `Vegetable`. ```scala // Definition of a trait. trait Recipe[+A] { def ingredients: List[A] } // Class definitions that extend Recipe class GenericRecipe(val ingredients: List[Food]) extends Recipe[Food] class VeggieRecipe(val ingredients: List[Vegetable]) extends Recipe[Vegetable] class GreenVeggieRecipe(val ingredients: List[GreenVeggie]) extends Recipe[GreenVeggie] ``` `Recipe` is a generic trait that accepts a covariant parameter (indicated by `[+A]`), and accepts a list of parameter type `A`. Three classes that extend `Recipe` were created: `GenericRecipe`, where `Recipe`'s type parameter is `Food`, `VeggieRecipe`, where `Recipe`'s type parameter is `Vegetable`, and`GreenVeggieRecipe`, where `Recipe`'s type parameter is `GreenVeggie`. ```scala // Function that accepts a Recipe with parameter Food, and prints out the ingredients def printRecipe(recipe: Recipe[Food]): Unit = println(recipe.ingredients.map(_.name)) // Creating instances of the different Recipes val generalRecipe = new GenericRecipe(List(Food("Chicken"), Food("Apple"))) val veggieRecipe = new VeggieRecipe(List(Vegetable("Carrot"), Vegetable("Lettuce"))) val greenVeggieRecipe = new GreenVeggieRecipe(List(GreenVeggie("Spinach"), GreenVeggie("Kale"))) printRecipe(generalRecipe) // List(Chicken, Apple) printRecipe(veggieRecipe) // List(Carrot, Lettuce) printRecipe(greenVeggieRecipe) // List(Spinach, Kale) ``` The function `printRecipe` is defined such that it accepts a `Recipe` object, with its parameter as `Food`. We can see that `printRecipe` accepts a `GenericRecipe`, `VeggieRecipe`, and `GreenVeggieRecipe` as its argument. This is what covariant types allow developers to acheieve. Assigning a direct relationship to generic classes allows for developers to acheieve this type of abstraction. The following image more closely details this covariance. ![](https://i.imgur.com/gHmt0hO.png) This image shows that `Food` is a parent class of `Vegetable`, which is a parent class of `GreenVeggie`. As we can see, by covariance, `Recipe[Food]` is a parent class of `Recipe[Vegetable]`, which is a parent class of `Recipe[GreenVeggie]` Now, we will consider a slightly different example. ```scala // Creation of abstract class Vehicle abstract class Vehicle { def name: String } // Creation of classes Car and Train, both of which extend Vehicle class Car(val name: String) extends Vehicle class Train(val name: String) extends Vehicle // Function that accepts a list of vehicles def printVehicleNames(vehicles: List[Vehicle]): Unit = vehicles.foreach { vehicle => println(vehicle.name) } val cars: List[Car] = List(Car("Toyota"), Car("Honda")) val trains: List[Train] = List(Train("Bombardier"), Train("GE")) printVehicleNames(cars) // prints: Toyota, Honda printVehicleNames(trains) // prints: Bombardier, GE ``` Note that in this example, we have that `Car` and `Train` are subclasses of `Vehicle`. The function `printVehicleNames` accepts `List[Vehicle]` as its input. By covariance, this means that `List[Train]` and `List[Car]` are also accepted, as we know that `Train` and `Car` are child classes to `Vehicle`. However, in this example, we did not indicate anywhere using the notation of `[+T]` as mentioned before. This is because `List`, as well as many other immutable types in Scala's standard library such as `Seq`, and `Vector` are defined to be covariant data types. ### Contravariance [comment]: # (we should mention that Scala does not support multiple inheritance, so ) Contravariance represents a relationship where the hierarchy of type parameters is reversed when the type parameter is passed into a generic type. This produces the opposite relationship than that of produced by covariance. If `A` is a *supertype* of `B`, and we have a generic type `G[T]` where `T` is contravariant, then `G[A]` is a *subtype* of `G[B]`. Notice, if `T` was covariant, then `G[A]` would be a *supertype* of `G[B]`. The following is a concrete example: ```scala abstract class Vehicle(name: String) class Car(val name: String) extends Vehicle(name) ``` This snippet defines an abstract `Vehicle` class with subclass `Car`. ```scala abstract class Mechanic[-VehicleType]: def fix(vehicle: VehicleType): Unit ``` The Mechanic generic class has the type parameter `VehicleType`. Notice the `-` in front of the type parameter. This is the syntax to define `Mechanic` as a contravariant type. ```scala val vehicleMechanic1: Mechanic[Vehicle] = null val carMechanic1: Mechanic[Car] = vehicleMechanic1 // Code compiles successfully ``` This example shows that a vehicle mechanic is also a car mechanic. Since `Vehicle` is a supertype of `Car`, one would expect a vehicle mechanic to also be able to fix a car. Since the parameter type of `Mechanic` is contravariant, `Mechanic[Vehicle]` is a subtype of `Mechanic[Car]`. Thus we can assign `carMechanic1` values of type `Mechanic[Vehicle]`, i.e `vehicleMechanic`. ```scala val carMechanic2: Mechanic[Car] = null val vehicleMechanic2: Mechanic[Vehicle] = carMechanic2 // Code errors out with the following message // Found: (Playground.carMechanic2 : Playground.Mechanic[Playground.Car]) // Required: Playground.Mechanic[Playground.Vehicle] ``` This example shows that a car mechanic cannot be assigned to a vehicle mechanic. A vehicle mechanic is expected to be able to fix all vehicles, however a car mechanic is only known to fix cars. `Mechanic[Car]` is a supertype of `Mechanic[Vehicle]` and a subtype cannot be assigned a variable of its supertype. The type relations in the example above is shown by this diagram: ![](https://i.imgur.com/HNIloHF.png) ### Invariance Now, consider the following snippet of code. ```scala class Food(val name: String) class Vegetable(override val name: String) extends Food(name) class GreenVeggie(override val name: String) extends Vegetable(name) // Definition of a trait. trait Recipe[A] { def ingredients: List[A] } // Class definitions that extend Recipe class GenericRecipe(val ingredients: List[Food]) extends Recipe[Food] class VeggieRecipe(val ingredients: List[Vegetable]) extends Recipe[Vegetable] class GreenVeggieRecipe(val ingredients: List[GreenVeggie]) extends Recipe[GreenVeggie] // Function that accepts a Recipe with parameter Food, and prints out the ingredients def printRecipe(recipe: Recipe[Food]): Unit = println(recipe.ingredients.map(_.name)) // Creating instances of the different Recipes val generalRecipe = new GenericRecipe(List(Food("Chicken"), Food("Apple"))) val veggieRecipe = new VeggieRecipe(List(Vegetable("Carrot"), Vegetable("Lettuce"))) val greenVeggieRecipe = new GreenVeggieRecipe(List(GreenVeggie("Spinach"), GreenVeggie("Kale"))) printRecipe(generalRecipe) printRecipe(veggieRecipe) printRecipe(greenVeggieRecipe) ``` Examine this code closely. On first glance, it might appear to be the same segment of code as the first one provided, but that is not quite correct. When defining the trait with generic `A`, it is no longer indicated as `[A+]`. This minor change in the code causes the code to no longer compile, as the function calls `printRecipe(veggieRecipe)` and `printRecipe(greenVeggieRecipe)` are now invalid. The reason for this is that the indicator that `Recipe` is covariant no longer exists, meaning that there is no longer a covariant relationship. Now, `Recipe[GreenVeggie]` is no longer a subclass of `Recipe[Vegetable]`, and `Recipe[GreenVeggie]` and `Recipe[Vegetable]` are no longer subclasses of `Recipe[Food]`, explaining why these function calls are no longer valid. This example describes an invariant relationship, as a developer cannot assume any relationships for a generic class with a type parameter that is known to have subclasses or superclasses. For a generic class `G[T]`, we know that `T` is invariant, since `T` does not have `+` or `-` as a prefix. ### Use Cases of Varaince Relationships #### Liskov substitution principle Variance relationships extend subtype relationships between classes into subtype relations between generic types with the same classes. This additional information allows for Liskov substitution principle to be applicable when dealing with generics. #### Producers and Consumers Variance relations might seem unintutive initially, however, there are heuristics that make it clear if a type parameter should be covariant, contravariant or invariant. In general, if a generic type can be viewed as a "producer" from the perspective of the type parameter, then the type parameter is covariant. For example, a the built-in `List[T]` class's type parameter `T` is covariant, since a list of type `A` can also contain a subtype `B`. Another example can be that of `R`. In general, if a generic type can be viewed as a "consumer" from the perspective of the type parameter, then the type parameter is covariant. Consider, generic `FoodConsumer[T]`, where `T` represents the type of food the food consumer can eat. If a food consumer can eat salmon, it also eat fishs. Thus given `Fish` and its subtype `Salmon`, `FoodConsumer[Fish]` is a subtype of `FoodConsumer[Salmon]`. ### Conculsion When dealing with generic classes, it is not a universal trait for a language to have type variances. Scala's optional usage of this feature gives developers a very useful feature to conceptually think about the relationships they are forming in when dealing with Object Oriented Programming and Generics. It also is useful to allow another level of abstraction, resulting in more expressive and concise code. In general, variance in type relationships can be classified as covariance, contravariance, and invariance. Consider generic class `G` with parameter type `T`, when given classes `A` and `B`. The parameter types are covariant if `B` is a subtype of `A` implies that `G[B]` is a subtype of `G[A]`. The parameter types are contravariant if `B` is a subtype of `A` implies that `G[B]` is a supertype of `G[A]`. The parameter types are invariant if neither of the previous classifications apply. ### Additional Resources [comment]: # (Should we use MLA Citations for this?) 1. [Scala Documentation](https://docs.scala-lang.org/) 2. [Variance in Scala](https://docs.scala-lang.org/scala3/book/types-variance.html) 3. [Functional Programming in Scala](https://docs.scala-lang.org/overviews/scala-book/functional-programming.html) 4. [Interview with Scala creator Martin Odersky](https://www.lightbend.com/company/news/jaxenter-interview-with-scala-creator-martin-odersky-on-the-current-state-of-scala)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully