相互排斥的特征

有没有办法来定义一个通用类型的替代品的集合:

trait Mutability
trait Mutable extends Mutability
trait Immutable extends Mutability

并让编译器排除如下内容:

object Hat extends Mutable with Immutable

我相信我可以通过拥有一个共同的冲突成员来强制执行一些编译器错误,但是错误消息有点偏斜:

trait Mutability
trait Mutable extends Mutability { protected val conflict = true }
trait Immutable extends Mutability { protected val conflict = true }

object Hat extends Mutable with Immutable

<console>:10: error: object Hat inherits conflicting members:
value conflict in class Immutable$class of type Boolean  and
value conflict in class Mutable$class of type Boolean
(Note: this can be resolved by declaring an override in object Hat.)
   object Hat extends Immutable with Mutable

是否有一种更直接的方式来表达这种约束,并且不允许某人通过采用编译器提供的提示来解决它(重写在Hat中的'冲突')?

感谢您的任何见解


我认为这可能有效

sealed trait Mutability
case object Immutable extends Mutability
case object Mutable extends Mutability

trait MutabilityLevel[A <: Mutability]

class Foo extends MutabilityLevel[Immutable.type]

这个(ab?)使用的事实是,你不能用不同的参数化扩展相同的特征两次

scala> class Foo extends MutabilityLevel[Immutable.type] with MutabilityLevel[Mutable.type]
<console>:11: error: illegal inheritance;
 self-type Foo does not conform to MutabilityLevel[Immutable.type]'s selftype MutabilityLevel[Immutable.type]
       class Foo extends MutabilityLevel[Immutable.type] with MutabilityLevel[Mutable.type]
                         ^
<console>:11: error: illegal inheritance;
 self-type Foo does not conform to MutabilityLevel[Mutable.type]'s selftype MutabilityLevel[Mutable.type]
       class Foo extends MutabilityLevel[Immutable.type] with MutabilityLevel[Mutable.type]

然而..

scala> class Foo extends MutabilityLevel[Mutability]
defined class Foo
链接地址: http://www.djcxy.com/p/27101.html

上一篇: mutually exclusive traits

下一篇: Formatting Flask app logs in json