Does a class with a self type of another class make sense?
Asked Answered
A

1

6
scala> class A
defined class A

scala> class B {this: A => }
defined class B

scala> new B
<console>:10: error: class B cannot be instantiated because it does not conform
to its self-type B with A
             new B
             ^

Class B sets the self type to class A, therefore class B (or a subclass of it) has to extend class A to create an instance of B. But is this possible at all, since a subclass of B can only extend one class (and this is class B) ?

So this leads me to the question, does it make sense to declare the self type of a class to another class in any case ?

Apiculture answered 30/6, 2012 at 12:33 Comment(0)
O
10

You are right with the observation that this definition can not lead to a concrete implementation, as you cannot mix two classes, only traits. So the short answer is 'no', either should be a trait.

There are several questions on Stackoverflow regarding self-types. Two useful ones are these:

In the second question, there is a good answer by Ben Lings who cites the following passage from the blog of Spiros Tzavellas:

In conclusion, if we want to move method implementations inside traits then we risk polluting the interface of those traits with abstract methods that support the implementation of the concrete methods and are unrelated with the main responsibility of the trait. A solution to this problem is to move those abstract methods in other traits and compose the traits together using self type annotations and multiple inheritance.

For example, if A (assume it's a trait and not a class now!) is a logger. You don't want to expose for B publicly the logging API mixed in by A. Therefore you would use a self-type and not mixin. Within the implementation of B you can call into the logging API, but from the outside it is not visible.


On the other hand, you could use composition in the following form:

trait B {
    protected def logger: A
}

The difference now is that

  • B must refer to logger when wanting to use its functionality
  • subtypes of B have access to the logger
  • B and A do not compete in namespace (e.g. could have methods of the same name without collision)

I would say that self-types are a fairly peripheral feature of Scala, you don't need them in many cases, and you have options like this to achieve almost the same without self-types.

Oppose answered 30/6, 2012 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.