Possible Duplicate:
Scala: Abstract Types vs Generics
Chapter 20.6 'Abstract types' of 'Programming in Scala' explains the use of an abstract type with an example that ends in the following resulting code:
class Food
abstract class Animal {
type SuitableFood <: Food
def eat(food: SuitableFood)
}
class Grass extends Food
class Cow extends Animal {
type SuitableFood = Grass
override def eat(food: Grass) {}
}
With these definitions, an object of Cow
can not eat a fish:
class Fish extends Food
val bessy: Animal = new Cow
bessy eat (new Fish) // Error, type mismatch
After reading this good example about the use of an abstract type, I was wondering, why we do not just use a type parameter instead ?
class Food
abstract class Animal[T <: Food] {
def eat(food: T)
}
class Grass extends Food
class Cow extends Animal[Grass] {
override def eat(food: Grass){}
}
class Fish extends Food
val bessy: Animal[Grass] = new Cow
bessy eat (new Fish) // Also ends in a type mismatch error !
Where is the difference using type parameter instead of an abstract type here ?