TypeSafe Journey Using Scala
  • Table Of Content
  • About This Book
  • Copyleft Notice
  • Thanks
  • My Journey
  • Introduction
  • Phase I: Basics
    • Chapter 1: What are the types?
    • Chapter 2: Types Vs Classes and Subtyping Vs Inheritance
    • Chapter 3: Type Disciplines
    • Chapter 4: Type Inference
    • Chapter 5: Scala Types Hierarchy
    • Chapter 6: Parameterized Types
    • Chapter 7: Type Erasure
    • Chapter 8: Type Classes and Ad-hoc Polymorphism
    • Chapter 9: Type Constraints
    • Chapter 10: Variance
      • Non-Variance
      • Co-Variance
      • Contra-Varaince
      • Conclusion
  • Phase II: Advance
    • Chapter 11: What are Kinds in Scala?
    • Chapter 12: Higher Kinded Types
Powered by GitBook
On this page
  1. Phase I: Basics
  2. Chapter 10: Variance

Non-Variance

Non-Variance is the most basic and easiest variance on parameterized types. According to non-variance or we can say in-variance there is no relationship between any of two parameterize type (as shown in diagram 10.1), even their type constructor accepts those parameters which have some inheritance hierarchy like our previous example Garage[Lamborghini] is completely different type from Garage[Car] even Car is a supertype of Lamborghini. By default when we creating our parameterized types they are non-variant.

class Basket[T](fruitsOrVeg : T) {
	def addTheFuritOrVeg(fruitsOrVeg : T) : Unit = { … }
}

class Fruit
class Apple extends Fruit
class Orange extends Fruit

new Basket[Fruit]
new Basket[Apple]
new Basket[Orange]

We are creating three new parameterize type objects which are completely different from each other even Fruit have an inheritance hierarchy.

PreviousChapter 10: VarianceNextCo-Variance

Last updated 6 years ago