7
votes

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.

1
You missed out trying to actually create an instance of D, do that and see what happens.johanandren
The type of self is D with C. I'm not sure if there's a use case besides documentation.som-snytt
that is my question, if create an instance of D, there is an compilation error. new D with C <console>:10: error: class C needs to be a trait to be mixed in new D with CXiaohe Dong
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.user4322779

1 Answers

0
votes

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.