强制 Scala 特性不兼容

Force Scala traits to be incompatible

有没有办法阻止两个特征混合成 class 在一起?

我知道您可以使用自我类型注释来要求特征只能混合到特定类型的 class 中,但是您可以使用类似的构造来要求目标 class不混合特定特征?

例如:

abstract class Collector(p: Boolean)

trait Cache

trait ACache extends Cache { self: Collector => }

trait BCache extends Cache { self: Collector => }

我能否要求 Collector 的任何实现混合在 ACacheBCache 中,或者没有任何缓存特征,但不是 ACacheBCache同时?

class GoodCollector(p: Boolean) extends Collector(p) with ACache //legal
class BadCollector(p: Boolean) extends Collector(p) with ACache with BCache //illegal

如果您像这样更改 Cache

trait Cache[A <: Cache[_]]

trait ACache extends Cache[ACache] { self: Collector =>
}

trait BCache extends Cache[BCache] { self: Collector =>
}

然后:

class BadCollector(p: Boolean) extends Collector(p) with ACache with BCache 

将失败:

illegal inheritance; class BadCollector inherits different type instances of trait Cache: Cache[BCache] and Cache[ACache] class BadCollector(p: Boolean) extends Collector(p) with ACache with BCache