简体   繁体   English

特质自我类型绑定:A与B但不与A与C

[英]Trait self type bound: A with B but not A with C

Say I have: 说我有:

abstract class D[T] {}
trait A[T] { self => D[T] without B }
trait B[T] { self => D[T] without A }

Bottom line, B cannot be mixed into D if it already extends 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

How can I correctly enforce this type bound? 如何正确执行此类型绑定?

There is a way to do this, though I don't know if it's the only / preferred way. 有一种方法可以做到这一点,虽然我不知道它是否是唯一/首选方式。

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
                  ^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM