说我有:
abstract class D[T] {}
trait A[T] { self => D[T] without B }
trait B[T] { self => D[T] without A }
如果已经扩展B
,则无法将A
混合到D中。
class Test extends D[String] with B[String] // ok
class Test2 extends D[String] with A[String] // ok
class Test3 extends D[String] with A[String] with B[whatever] // bad
class Test4 extends D[String] with B[String] with A[whatever] // bad
如何正确执行此类型绑定?
答案 0 :(得分:6)
有一种方法可以做到这一点,虽然我不知道它是否是唯一/首选方式。
sealed trait Z[T <: Z[T]]
trait A extends Z[A] { this: D => }
trait B extends Z[B] { this: D => }
scala> new D with A
res6: D with A = $anon$1@7e7584ec
scala> new D with B
res7: D with B = $anon$1@7537e98f
scala> new D with A with B
<console>:15: error: illegal inheritance;
anonymous class $anon inherits different type instances of trait Z:
Z[B] and Z[A]
new D with A with B
^