7

I know Scala can only mixin traits, it makes sense for dependency injection and cake pattern. My question is why I can still declare a class which need another "class" but not trait.

Code:

class C
class D { self : C =>}

This is still complied successfully. I thought it should failed compiled, because at this point how can new instance D (C is class not trait).

Edit:

when try to instantiate D:

new D with C //compilation fail class C needs to be a trait to be mixed in.

Xiaohe Dong
  • 4,953
  • 6
  • 24
  • 53
  • 1
    You missed out trying to actually create an instance of D, do that and see what happens. – johanandren Mar 28 '14 at 09:59
  • The type of `self` is `D with C`. I'm not sure if there's a use case besides documentation. – som-snytt Mar 28 '14 at 11:32
  • that is my question, if create an instance of D, there is an compilation error. new D with C :10: error: class C needs to be a trait to be mixed in new D with C – Xiaohe Dong Mar 28 '14 at 13:53
  • Dzanvu provided a good answer. Note that traits are essentialy the same as classes without initialization capability. Self type definition can be useful to implement mutual dependency between a class that extends a trait with self-type set to the class. –  May 07 '15 at 08:04

1 Answers1

0

You should explicitly make class D to extends C as follows:

class C
class D extends C { self: C => }

Furthermore, you can refer to the post Does a class with a self type of another class make sense?, which explains this problem clearly.

Community
  • 1
  • 1
Dzanvu
  • 523
  • 7
  • 18