问题描述
我知道 Scala 只能混合特征,这对依赖注入和蛋糕模式很有意义.我的问题是为什么我仍然可以声明一个需要另一个类"但不需要特征的类.
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.
代码:
class C
class D { self : C =>}
这个还是编译成功了.我认为它应该编译失败,因为此时如何新建实例 D (C is class not trait).
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).
尝试实例化 D 时:
new D with C//编译失败类C需要是一个trait来混入.
new D with C //compilation fail class C needs to be a trait to be mixed in.
推荐答案
你应该明确地使 class D
成为 extends C
如下:
You should explicitly make class D
to extends C
as follows:
class C
class D extends C { self: C => }
此外,您可以参考帖子 一个类具有另一个类的 self 类型有意义吗?,这清楚地解释了这个问题.
Furthermore, you can refer to the post Does a class with a self type of another class make sense?, which explains this problem clearly.
这篇关于为什么自类型类可以声明类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!