强迫Scala特征不相容
有没有办法阻止这两种特质混合在一起 我知道您可以使用自类型注释来要求一个trait只混合到一个特定类型的类中,但是您可以使用类似的构造来要求目标类不混合到一个特定trait中吗 例如:强迫Scala特征不相容,scala,inheritance,traits,Scala,Inheritance,Traits,有没有办法阻止这两种特质混合在一起 我知道您可以使用自类型注释来要求一个trait只混合到一个特定类型的类中,但是您可以使用类似的构造来要求目标类不混合到一个特定trait中吗 例如: abstract class Collector(p: Boolean) trait Cache trait ACache extends Cache { self: Collector => } trait BCache extends Cache { self: Collector => }
abstract class Collector(p: Boolean)
trait Cache
trait ACache extends Cache { self: Collector => }
trait BCache extends Cache { self: Collector => }
我是否可以要求Collector
的任何实现在ACache
、BCache
中混合使用,或者不使用任何缓存特性,但不能同时使用ACache
和BCache
class GoodCollector(p: Boolean) extends Collector(p) with ACache //legal
class BadCollector(p: Boolean) extends Collector(p) with ACache with BCache //illegal
如果您这样更改
缓存
:
trait Cache[A <: Cache[_]]
trait ACache extends Cache[ACache] { self: Collector =>
}
trait BCache extends Cache[BCache] { self: Collector =>
}
将在以下情况下失败:
非法继承;
类BadCollector继承特征缓存的不同类型实例:
缓存[BCache]和缓存[ACache]
类BadCollector(p:Boolean)用ACache和BCache扩展了收集器(p)
class BadCollector(p: Boolean) extends Collector(p) with ACache with BCache