乐趣区

Scala学习抽象类型

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)
退出移动版