-
Book Overview & Buying
-
Table Of Contents
Learning Scala Programming
By :
Both are forms of providing polymorphic abstractions in Scala. Mostly, it's a design choice whether you prefer one over the other. Talking about design choices, let's have a closer look. For that we'll take an example where we have two class hierarchies as follows:
abstract class Food
class Grass extends Food
class Meat extends Food
abstract class Animal {
type SuitableFood <: Food
def eatMeal(meal: SuitableFood)
} From the knowledge about abstract types and upper bounds we can say Animal is an abstract class, which has an abstract type member named SuitableFood, which expects only the Food type. If we declare two subtypes of Animal class namely Cow and Lion it could look like a cow can eat Grass as well as Meat because both are subclasses of Food. But this isn't the desired behavior. To resolve the issue, we can declare Cow like this:
class Cow extends Animal {
type SuitableFood <: Grass
override def eatMeal(meal: SuitableFood...