简体   繁体   English

使用`extends`调用特征中的超类型方法,但不允许使用自我类型

[英]Calls to supertype methods in traits allowed with `extends` but not with self-types

Consider: 考虑:

trait SuperBar { def superBarMethod = ??? }
trait Bar extends SuperBar

trait FooWithSelfType { this: Bar =>
  super.superBarMethod // error: value superBarMethod is not a member of AnyRef
}

trait FooWithExtends extends Bar {
  super.superBarMethod
}

Is this limitation due to some underlying implementation shortcoming, or it's actually designed this way for a reason? 这种限制是由于一些潜在的实现缺点,还是实际上是出于某种原因设计的?

The way I see this is that if this is known to be of type Bar , and Bar is known to be a subtype of SuperBar , then invoking any SuperBar methods on this should be allowed. 我看到这个问题的方法是,如果this是已知类型的Bar ,和Bar是已知的亚型SuperBar ,然后调用任何SuperBar上的方法this应该被允许。

FooWithSelfType might know that it is a Bar , but it's not actually part of FooWithSelfType 's inheritance hierarchy, so it doesn't have access to super except for the super that is explicitly part of its inheritance hierarchy. FooWithSelfType可能知道 ,这是一个Bar ,但它不是真正的一部分FooWithSelfType的继承层次结构,所以它不能够获得super除了super是明确的继承层次结构的一部分。 If you had 如果你有

trait Baz extends SuperBaz { this : Bar => 
  /* ... */
}

how would you know to what super refers if both SuperBaz and SuperBar were possibilities? 如果SuperBazSuperBar都有可能,你怎么知道super指的是什么?

Self-type says that the current trait should be mixed into is at most the type you are using as a self-type. 自我类型表示当前特征应该被混合到最多你使用的类型作为自我类型。 Meaning that all subtypes of that given type can mix the current trait. 意味着该给定类型的所有子类型都可以混合当前特征。 With that in mind, super only refers to the class/trait that the current trait is a sub class/trait of. 考虑到这一点,super仅指当前特征是子类/特征的类/特征。

I have to say that I ran into this thought not that long ago, and I think this could be a weakness, I mean we could imagine that the compiler could look up both methods in the superclass and those in the self-type's superclass. 我不得不说,不久前我遇到了这个想法,我认为这可能是一个弱点,我的意思是我们可以想象编译器可以查找超类中的两个方法和自我类型的超类中的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM