Scala - 相互排斥的特征

时间:2015-06-18 21:47:35

标签: scala traits

有没有办法定义常见类型的替代品集合:

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

是否有一种更直接的方式来表达这种约束,并且不允许某人通过采用编译器提供的提示来解决它(覆盖&#39;在帽子中的冲突&#39;)

感谢您的任何见解

1 个答案:

答案 0 :(得分:3)

我认为这可能有效

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
相关问题