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

斯卡拉 – 性状混合的限制

发布时间:2020-12-16 19:02:21 所属栏目:安全 来源:网络整理
导读:我想要有只能混合指定特征的课程: class Peter extends Human with Lawful with Evilclass Mag extends Elf with Chaotic with Neutral 在Scala中有办法吗? UPD: trait Lawtrait Lawful extends Lawtrait LNeutral extends Lawtrait Chaotic extends Lawt
我想要有只能混合指定特征的课程:

class Peter extends Human with Lawful with Evil
class Mag extends Elf with Chaotic with Neutral

在Scala中有办法吗?

UPD:

trait Law
trait Lawful extends Law
trait LNeutral extends Law
trait Chaotic extends Law

trait Moral
trait Good extends Moral
trait Neutral extends Moral
trait Evil extends Moral

class Hero .........
class Homer extends Hero with Chaotic with Good

我想以一种限制客户端程序员的方式定义一个Hero类,如果他扩展了Hero类,则会混合特定的特征(合法/ LNeutral / Chaotic和Good / Neutral / Evil).而且我想找到一些限制/限制客户端代码的其他可能性.

解决方法

强硬.尝试这个:

scala> trait Law[T]
defined trait Law

scala> trait Lawful extends Law[Lawful]
defined trait Lawful

scala> trait Chaotic extends Law[Chaotic]
defined trait Chaotic

scala> class Peter extends Lawful with Chaotic
<console>:8: error: illegal inheritance;
 class Peter inherits different type instances of trait Law:
Law[Chaotic] and Law[Lawful]
       class Peter extends Lawful with Chaotic
             ^

如果你想要一个法律类型必须扩展的要求,那么你需要在一些基类或特征中使用自己的类型:

scala> class Human {
     |   self: Law[_] =>
     | }
defined class Human

scala> class Peter extends Human
<console>:7: error: illegal inheritance;
 self-type Peter does not conform to Human's selftype Human with Law[_]
       class Peter extends Human
                           ^

还有一些进一步的调整来确保进一步的类型安全.最终结果可能如下所示:

sealed trait Law[T <: Law[T]]
trait Lawful extends Law[Lawful]
trait LNeutral extends Law[LNeutral]
trait Chaotic extends Law[Chaotic]

sealed trait Moral[T <: Moral[T]]
trait Good extends Moral[Good]
trait Neutral extends Moral[Neutral]
trait Evil extends Moral[Evil]

class Human {
  self: Law[_] with Moral[_] =>
}

(编辑:李大同)

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

    推荐文章
      热点阅读