O'Reilly logo

Learning Scala Programming by Vikash Sharma

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Variance under inheritance

One of the ways we can learn about a concept is to ask questions that lead you to the concept. So let's ask a question ourselves. Given that a Cat class type extends the Animal class, is it okay to treat a list of cats as a list of animals? Programmatically, see the following:

abstract class Animal() 
 
class Cat(name: String) extends Animal()               // Inheritance relationship between Cat and Animal 
 
def doSomethingForAnimals(animals: List[Animal]) = ??? //definitely do something for animals. 
 
Is it possible to pass an argument that's a list of Cats? 
val cats = List(new Cat("Mischief"), new Cat("Birdie")) 
doSomethingForAnimals(cats) 

If it's possible, the statement that List[Cat] is a subtype of List[Animal] makes sense. Also, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required