Scala - 相互排斥的特征

jmc*_*lty 7 scala traits

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

trait Mutability
trait Mutable extends Mutability
trait Immutable extends Mutability
Run Code Online (Sandbox Code Playgroud)

并让编译器排除类似的东西:

object Hat extends Mutable with Immutable
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

是否有更直接的方式来表达这种约束,并且不允许某人通过获取编译器提供的提示来解决它(在Hat中覆盖"冲突")?

感谢您的任何见解

Dae*_*yth 3

我认为这可能有用

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

trait MutabilityLevel[A <: Mutability]

class Foo extends MutabilityLevel[Immutable.type]
Run Code Online (Sandbox Code Playgroud)

这(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]
Run Code Online (Sandbox Code Playgroud)

然而..

scala> class Foo extends MutabilityLevel[Mutability]
defined class Foo
Run Code Online (Sandbox Code Playgroud)