10

我想拥有只能混合指定特征的类:

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

在 Scala 中可以做到这一点吗?

升级版:

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限制客户端程序员在扩展类时混合特定特征(Lawful/ LNeutral/ChaoticGood/ Neutral/ Evil)的方式定义一个Hero类。我想找到一些其他的可能性来限制/约束这样的客户端代码。

4

3 回答 3

28

艰难的。试试这个:

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
             ^

如果您想要求必须扩展 Law 类型,那么您需要在某些基类或 trait 中使用 self 类型:

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[_] =>
}
于 2010-04-28T15:36:27.390 回答
9

也许您正在寻找限制自我类型声明。例如:

class Human
trait Lawful
trait Lawless

class NiceGuy
extends Human
{
  this: Lawful =>
}

class BadGuy
extends Human
{
  this: Lawless =>
}


scala> class SuperHero extends NiceGuy
<console>:7: error: illegal inheritance;
 self-type SuperHero does not conform to NiceGuy's selftype NiceGuy with Lawful
       class SuperHero extends NiceGuy
                               ^

scala> class SuperHero extends NiceGuy with Lawful
defined class SuperHero

scala> class SuperVillain extends BadGuy
<console>:7: error: illegal inheritance;
 self-type SuperVillain does not conform to BadGuy's selftype BadGuy with Lawless
       class SuperVillain extends BadGuy
                                  ^

scala> class SuperVillain extends BadGuy with Lawless
defined class SuperVillain
于 2010-04-28T14:06:14.927 回答
0

您可以检查构造函数Human和/或Elf它是否是允许特征的实例:

class Human {
  if (this.instanceOf[Lawful] && this.instanceOf[Chaotic])
    throw new AlignmentException("A Human can only be either Lawful or Chaotic")
}
于 2010-04-28T14:11:00.483 回答