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

☆樱花仙子☆ 提交于 2019-11-30 20:48:13
0__

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.

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