Variance In Scala

Variance In Scala

1. All values have a type

2. Types have supertype relationships up to Any

3. Types have subtype relationships down to Nothing

4. References can store subclass instances (polymorphism)

Variance example: List[T]

  1. Container: List is a container of type List.
  2. Content: the content of List(Container) will be type T.
  3. A container can store the content.

In general, there are three modes of variance:

  • invariant—the default, written like List[T]
  • covariant—annotated with a +, written like List[+T]
  • contravariant—annotated with a -, written like List[-T]

To understand Variance, we must consider the container and the content.

Polymorphism: We can store the child class in the parent class reference.

Considering the following relation let's understand variance:

Example 1: In-Variance

Example 2: Co-Variance

Example 3: Contra-Variance

GitHub: https://github.com/anish-diliyan/core-scala/tree/master/src/main/scala/generics



要查看或添加评论,请登录

Anish Kumar的更多文章

  • Understanding Functor

    Understanding Functor

    Functor represents a data structure or context that can be mapped over. It provides a way to apply a function to the…

    1 条评论
  • Monad For Beginners

    Monad For Beginners

    Monads are a fundamental concept in functional programming that represents computations that can be composed and…

  • def vs val To Define Abstract Members

    def vs val To Define Abstract Members

    The short story is that if you want to declare an abstract member in a trait, as a def or val field that may be later…

  • Basic Hierarchy of Scala Cat

    Basic Hierarchy of Scala Cat

  • Sorting in Scala: sorted method

    Sorting in Scala: sorted method

    Sorting in Scala is very similar to sorting in Java like Java's Comparable called Ordered and Java's Comparator called…

  • Anonymous Function: LAMBDA

    Anonymous Function: LAMBDA

    Dream: Use the function as a first-class element like val and var, which can be passed to the function as parameters…

  • Diamond Problem

    Diamond Problem

    The Diamond Problem occurs when a class inherits from two or more parent classes with the same method or field. This…

  • Match Patterns For Scala Classes

    Match Patterns For Scala Classes

    Pattern matching on case classes is straightforward because it provides extractor patterns out of the box. If we need…

  • Commonly Used Short Hands

    Commonly Used Short Hands

    infix/operator notation: A method with a single parameter can be used as an operator prefix notation: unary_prefix…

  • Partial Function In Scala

    Partial Function In Scala

    val aFunction = (x: Int) => x + 1 Here aFunction is an instance of Function1[Int, Int] ===== (Int) => (Int) which will…

社区洞察

其他会员也浏览了