19

Apart from the inheritance aspect, is there a difference between the following class templates:

1| trait TraitA extends TraitB

2| trait TraitA { self: TraitB => }

I would like to split responsibilities between TraitA and TraitB but the former cannot function without the latter.

How would you express this intent? To me solution [2] would be the more natural approach. However I do not want to put the burden on implementers mixing in what needs to be mixed in anyway.

Tim Friske
  • 2,012
  • 1
  • 18
  • 28
  • possible duplicate of [What is the difference between scala self-types and trait subclasses?](http://stackoverflow.com/questions/1990948/what-is-the-difference-between-scala-self-types-and-trait-subclasses) – om-nom-nom Jan 08 '13 at 00:42

1 Answers1

16

My preference is generally [1] because, as you say, the implementor is not burdened to mix in (a sub-type of) TraitB. Perhaps [2] is preferable if, for some reason, it is desirable not to inherit the concrete implementations in TraitB and force the implementor to make a choice among sub-types of TraitB. Still, [1] is just as flexible.

I tend to use [2] only where necessary, such as when the type isn't a known class or trait,

// Here, Matrix cannot extend type parameter Repr
trait Matrix[+Repr <: Matrix[Repr]] { self: Repr =>
  ...
}

Update. Here's another minor difference,

trait B
trait A { self: B => }
def g(ab: A): B = ab // Type mismatch: found A, required B

It's a little annoying an optional restriction not to be able to use A as a B, even though the type is incorporated.

Kipton Barros
  • 21,002
  • 4
  • 67
  • 80
  • 2
    Speaking about your update. I think that "little annoyance" is quite useful to let one express that an `A` "cooperates with" but at the same time "is not" a `B`. For me that's kind of like private vs. public inheritance respectively. – Tim Friske Aug 31 '11 at 22:24
  • Historically, the motivation for self-type annotation is the first difference—at least, that's how this feature is motivated in the paper *Scalable Component Abstractions* by Odersky&Zenger (which you can find on Google Scholar, if interested). – Blaisorblade Jul 02 '12 at 02:49