加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

组织Scala中的枚举

发布时间:2020-12-16 19:02:48 所属栏目:安全 来源:网络整理
导读:对于长期的问题抱歉: 说我有动物列表,我想把它们分开,如下所示: BasicAnimal = {Cat,Dog}Carnivore = {Cat,Dog,Dragon}Herbivore = {Cat,Horse} 现在,这些动物也要住在某个地方.所以有一个 BasicShelter with a method shelter(animal: BasicAnimal)Den wi
对于长期的问题抱歉:

说我有动物列表,我想把它们分开,如下所示:

BasicAnimal = {Cat,Dog}
Carnivore = {Cat,Dog,Dragon}
Herbivore = {Cat,Horse}

现在,这些动物也要住在某个地方.所以有一个

BasicShelter with a method shelter(animal: BasicAnimal)
Den with a method shelter(animal: Carnivore)
Shed with a method shelter(animal: Herbivore)

在Scala中实现这一点的最好方法是什么?一个尝试是:

class BasicAnimal extends Enumeration{
   val Cat,Dog = Value
}
class Carnivore extends BasicAnimal{
   val Dragon = Value
}
class Herbivore extends BasicAnimal{
   val Horse = Value
}

接着

class BasicHouse{
  def shelter(animal: BasicAnimal) = {//lots of code}
}
class Den{
  def shelter(animal: Carnivore) = {
  //again lots of code,but the cases dealing with Cat and Dog can be relegated to super.shelter
  }
}
class Shed{
  //the same
}

可悲的是,这不行.来自食肉动物的狗与BasicAnimal中的狗不同.那就是Carnivore.Dog == BasicAnimal.Dog返回false,所以在Den中重用BasicHouse中的代码的唯一方法是使用一个比较简单的等价方法来比较枚举的字符串(或类似的东西).它的作品,但它是非常不洁净.你能看到其他的可能性吗?

解决方法

根据@ paradigmatic的答案,但有几个增强:

sealed abstract trait BasicAnimal
sealed abstract trait Carnivore extends BasicAnimal
sealed abstract trait Herbivore extends BasicAnimal
sealed abstract trait Omnivore extends Carnivore with Herbivore

case object Dog extends Omnivore
case object Cat extends Omnivore
case object Dragon extends Carnivore
case object Horse extends Herbivore

使特征抽象允许您利用模式匹配中的完整性检查(否则会警告,不尝试对特征本身进行匹配)

Omnivore特征删除一些重复,并且也有助于模式匹配

使用扩展而不是自我打字只是更清洁,更直观

case对象而不是对象主要是为了更好地记录代码的意图,同时也提供了一个理性的toString实现

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读