Scala学习:抽象类型
type
现实与代码不兼容的问题
先抛出一个现实与代码不兼容的问题。
以下代码奶牛吃草是正常的,但你把鱼也喂给奶牛,它竟然也吃起来了。这显然是不合理的。
scala通过type
抽象类型解决这个问题
class Food
class Grass extends Food{
override def toString: String = "草"
}
class Fish extends Food{
override def toString: String = "鱼"
}
abstract class Animal{
def eat(food: Food)
}
class Cow extends Animal {
override def eat(food: Food): Unit = println(s"奶牛吃 $food")
}
val cow = new Cow
cow.eat(new Grass)
cow.eat(new Fish)
使用type解决不兼容问题
class Food
class Grass extends Food{
override def toString: String = "草"
}
class Fish extends Food{
override def toString: String = "鱼"
}
abstract class Animal{
type SuitableFood <: Food
def eat(food: SuitableFood)
}
class Cow extends Animal {
override type SuitableFood = Grass
override def eat(food: Grass): Unit = println(s"奶牛吃 $food")
}
val cow = new Cow
cow.eat(new Grass)
cow.eat(new Fish)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。