scala - 性状混合的限制

标签 scala traits

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

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/{11045}) 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
             ^

如果您想要求必须扩展 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
                           ^

还有一些进一步的调整以确保进一步的类型安全。最终结果可能如下所示:
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[_] =>
}

关于scala - 性状混合的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2729506/

相关文章:

scala - 如果 csv 列标题包含空格,则在 Spark 中将 csv 转换为 parquet 会出错

java - 弗林克 : possible to delete Queryable state after X time?

scala - 使用 nio 的客户端套接字的套接字管理器

python - 特征列表处理程序不响应 += 列表扩展

scala - 如何深度复制混合了特征的类

scala - 延迟特征初始化

scala - akka HttpResponse将主体读取为String scala

Scala:目的就像特征上的后缀,例如IndexSequenceLike

php - Codeigniter 3 : How to use composer packages?(Twilio SDK)

php - 如果可以使用接口(interface)和特征,为什么 PHP 有抽象类?