Does a class with a self type of another class make sense?

点点圈 提交于 2019-11-30 04:45:50

问题


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 ?


回答1:


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:

  • What is more Scala idiomatic: trait TraitA extends TraitB or trait TraitA { self: TraitB => }
  • Difference between trait inheritance and self type annotation

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.



来源:https://stackoverflow.com/questions/11274106/does-a-class-with-a-self-type-of-another-class-make-sense

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!