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
将 self 类型设置为 class A
,因此类 B
(或其子类)必须扩展类 A
创建 B
的实例.但这是否可能,因为 B
的子类只能扩展一个类(这是类 B
)?所以这让我想到了一个问题,在任何情况下将一个类的 self 类型声明为另一个类是否有意义?
最佳答案
您的观察是正确的,该定义不能导致具体的实现,因为您不能混合两个类,只能混合特征。所以简短的回答是“不”,两者都应该是一个特征。
Stackoverflow 上有几个关于 self-types 的问题。两个有用的是这些:
在第二个问题中,Ben Lings 给出了一个很好的答案,他引用了 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.
例如,如果
A
(假设它现在是一个特征而不是一个类!)是一个记录器。您不想为 B
公开公开混入的日志 API A
.因此,您将使用 self-type 而不是 mixin。内执行B
您可以调用日志记录 API,但从外部看它是不可见的。另一方面,您可以使用以下形式的组合:
trait B {
protected def logger: A
}
现在的区别在于
B
必须引用logger
想要使用其功能时 B
的亚型有权访问 logger
B
和 A
不要在命名空间中竞争(例如可以有相同名称的方法而不会发生冲突)我会说自类型是 Scala 的一个相当外围的特性,在很多情况下你不需要它们,并且你有这样的选择来实现几乎相同的无自类型。
关于scala - 具有另一个类的 self 类型的类是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11274106/