1

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)

小鸡
214 声望24 粉丝

1.01的365次方=37.8


引用和评论

0 条评论