[英]Self in trait invisible from outside the trait?
trait A { def someMethod = 1}
trait B { self : A => }
val refOfTypeB : B = new B with A
refOfTypeB.someMethod
The last line results in a type mismatch error. 最后一行导致类型不匹配错误。 My question is: why it's impossible to reach the method (of A) when it's given that B is also of type A?
我的问题是:当给出B也是A型时,为什么不可能达到(A)的方法?
So B
is not also of type A
. 所以
B
也不是A
型。 The self type annotation that you've used here indicates specifically that B
does not extend A
but that instead, wherever B
is mixed in, A
must be mixed in at some point as well. 你在这里使用的自我类型注释特别指出
B
不扩展A
但是相反,无论何时混入B
, A
必须在某一点混合。 Since you downcast refOfTypeB
to a B
instead of B with A
you don't get access to any of type A
's methods. 由于您
B with A
refOfTypeB
向下转换为B
而不是B with A
您无法访问任何类型A
的方法。 Inside of the implementation of the B
trait you can access A
's methods since the compiler knows that you'll at some point have access to A
in any implemented class. 在
B
trait的实现中,您可以访问A
的方法,因为编译器知道您在某些时候可以在任何已实现的类中访问A
It might be easier to think about it as B
depends on A
instead of B
is an A
. 考虑它可能更容易,因为
B
取决于A
而不是B
是A
For a more thorough explanation see this answer: What is the difference between self-types and trait subclasses? 有关更全面的解释,请参阅以下答案: 自我类型和特质子类之间有什么区别?
The problem is when you declare refOfTypeB, you have type B specified but not type B with A. 问题是当你声明refOfTypeB时,你指定了类型B但没有指定类型B和A.
The self => syntax allow you to access the properties of A within B and pass the compilation. self =>语法允许您访问B中的A属性并传递编译。
However, in the runtime, refOfTypeB is not recognize as B with A and the compiler doesn't necessarily have the function map correctly. 但是,在运行时,refOfTypeB不会被识别为带有A的B,并且编译器不一定正确地具有功能映射。
So, the correct syntax should be: 所以,正确的语法应该是:
trait A { def someMethod = 1}
trait B { self : A => }
val refOfTypeB : B with A = new B with A
refOfTypeB.someMethod //1
Indeed, this is more expressive in terms of explaining with what refOfTypeB exactly is. 实际上,这在解释refOfTypeB究竟是什么方面更具表现力。
This is the somehow the boilerplate of cake patterns. 这就是蛋糕模式的样板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.