为什么在调用受约束特征的方法时不查找自身类型?
假设
trait A { def t : Int }
trait B { this: A => }
为什么编译器不“知道”我可以在 B
上调用 t
?
def test(b: B): Int = b.t // doesn't work
但我(显然是多余的?)需要做
def test(b: B with A): Int = b.t
Assuming
trait A { def t : Int }
trait B { this: A => }
why is it that the compiler doesn't "know" that I can call t
on B
?
def test(b: B): Int = b.t // doesn't work
but that I (apparently redundantly?) need to do
def test(b: B with A): Int = b.t
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
自我类型不是特征或阶级契约的一部分。也就是说,它们不提供对特征或类的外部可见限制,仅提供内部可见的限制。自类型在对象实例化时进行检查,但只能由声明特征或任何继承特征/类/对象使用。用 Java 术语来说,您可以将自类型视为类似由特征声明的受保护接口(尽管 Java 当然实际上并不支持这样的东西)。
如果您希望测试成功,您需要使 B 对 A 的依赖从外部可见。这是通过“扩展”声明完成的,也称为简单子类化
Self-types are not part of the contract of a trait or class. That is to say, they don't provide externally visible restrictions on a trait or class, only internally visible ones. Self-types are checked at object instantiation time, but are otherwise only usable by the declaring trait or any inheriting traits/classes/objects. In Java terms, you could think of a self-type as being something like a a
protected interface
declared by the trait (although Java of course doesn't actually support such a thing).If you wanted your test to work, you would need to make the dependence of B on A externally visible. This is done with an "extends" declaration, a.k.a. simple subclassing