Scala中的抽象类型 [英] abstract type in scala

查看:132
本文介绍了Scala中的抽象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 Scala 中浏览抽象类型,但出现错误

I am just going through abstract type in Scala and I got an error

我正在尝试的示例:

scala> class Food
abstract class Animal {
type SuitableFood <: Food
def eat(food: SuitableFood)
}
defined class Food
defined class Animal

scala> class Grass extends Food
class Cow extends Animal {
type SuitableFood = Grass
override def eat(food: Grass) {}
}
defined class Grass
defined class Cow

scala> class Fish extends Food
defined class Fish

scala> val bessy: Animal = new Cow
bessy: Animal = Cow@5c404da8

scala> bessy.eat(new bessy.SuitableFood)
<console>:13: error: class type required but bessy.SuitableFood found
              bessy.eat(new bessy.SuitableFood)
                                  ^

scala> bessy.eat(bessy.SuitableFood)
<console>:13: error: value SuitableFood is not a member of Animal
              bessy.eat(bessy.SuitableFood)

scala> bessy.eat(new Grass)
<console>:13: error: type mismatch;
 found   : Grass
 required: bessy.SuitableFood
              bessy.eat(new Grass)

这些错误是什么?

为什么我不能将 new Grass 传递给 eat 方法作为参数,当我创建类似

Why can't I pass new Grass to the eat method as an argument, and when I create an object like

scala> val c=new Cow
c: Cow = Cow@645dd660


scala> c.eat(new Grass)

您能给我一些想法吗?

推荐答案

当您分配 bessy 时,您会c弃 Cow 实例到 Anmial

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

val bessy: Animal = new Cow

所以从静态的角度来看, bessy 动物,因此是 bessy.SuitableFood 的摘要。现在要纠正错误:

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


  1. 您不能使用 new 。

  2. bessy.SuitableFood 尝试访问值成员 SuitableFood (即def / val)

  3. 因为 bessy 是唯一的动物 ,您(静态)不知道它是否可以吃

  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
}

并实施:

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

现在您可以致电(在任何 Animal 上) :

Now you may call (on any Animal):

bessy.eat(bessy.makeFood())

这篇关于Scala中的抽象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆