加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:54:41 所属栏目:安全 来源:网络整理
导读:说我有: abstract class D[T] {}trait A[T] { self = D[T] without B }trait B[T] { self = D[T] without A } 底线,如果B已经延伸,则B不能混入D. class Test extends D[String] with B[String] // okclass Test2 extends D[String] with A[String] // okcla
说我有:

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

底线,如果B已经延伸,则B不能混入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

如何正确执行此类型绑定?

解决方法

有一种方法可以做到这一点,但我不知道它是否是唯一/首选方式.

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
                  ^

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读