Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trait self type bound: A with B but not A with C

Tags:

scala

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.

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?

like image 994
flavian Avatar asked Feb 03 '14 14:02

flavian


1 Answers

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
                  ^
like image 90
drexin Avatar answered Nov 13 '22 05:11

drexin