abstract type in scala

烈酒焚心 提交于 2019-12-05 17:21:35

When you assign bessy, you upcast the Cow instance to an Anmial:

val bessy: Animal = new Cow

So from a static point of view, bessy is an Animal and therefore bessy.SuitableFood abstract. Now to the errors:

  1. You cannot create an object of an abstract type with new.
  2. bessy.SuitableFood tries to access the value-member SuitableFood (i.e. def/val)
  3. Since bessy is "only" an Animal, you don't know (statically) if it can eat Grass.

What you can do, is add a method to Animal that allows you to create food:

abstract class Animal {
  type SuitableFood <: Food
  def eat(food: SuitableFood)
  def makeFood(): SuitableFood
}

And implement:

class Cow extends Animal {
  type SuitableFood = Grass
  override def eat(food: Grass) {}
  override def makeFood() = new Grass()
}

Now you may call (on any Animal):

bessy.eat(bessy.makeFood())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!