gpt4 book ai didi

scala - 特质 self 类型绑定(bind): A with B but not A with C

转载 作者:行者123 更新时间:2023-12-04 18:42:44 24 4
gpt4 key购买 nike

说我有:

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

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

最佳答案

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

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
^

关于scala - 特质 self 类型绑定(bind): A with B but not A with C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21530036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com