我想要的课程只能混合指定的特征:
class Peter extends Human with Lawful with Evil
class Mag extends Elf with Chaotic with Neutral
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
我想定义一个Hero在限制客户端程序员混合特定性状的方式类(Lawful/ LNeutral/ Chaotic和Good/ Neutral/ Evil),如果他扩展了Hero类.我想找到一些限制/约束客户端代码的其他可能性.
Dan*_*ral 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
^
Run Code Online (Sandbox Code Playgroud)
如果要使Law类型必须扩展,那么您需要在某些基类或特征中使用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
^
Run Code Online (Sandbox Code Playgroud)
还有一些进一步的调整,以确保进一步的类型安全.最终结果可能如下所示:
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[_] =>
}
Run Code Online (Sandbox Code Playgroud)
也许你正在寻找限制自我类型的声明.例如:
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
Run Code Online (Sandbox Code Playgroud)