问题描述
this aliasing
和self type
之间是否存在任何关系?this aliasing
是self type
的特例吗?在scala 2nd P776中进行编程时,作者说:
Is there any relationship between this aliasing
and self type
?Is this aliasing
a special case of self type
?In programming in scala 2nd P776, the author said:
您在第29.4节中看到了这样的语法,该语法用于提供一个 将自身类型转化为特质.
You saw syntax like this in Section 29.4, where it was used to give a self type to a trait.
但是,自我类型的语法看起来不是这样,
but, the syntax for self type doesn't look like this, it's like:
还有另一个问题是为什么this aliasing
有用吗?我看不到给this
引用起别名的任何意义,因为它已经是当前对象引用的常规别名,但是在Play框架的源代码中,我看到了很多代码(尤其是anorm部分),例如:
And another question is why this aliasing
is useful? I can't see there's any sense to give this
reference an alias, because it's already a conventional alias for the current object reference, however in the Play framework source code, I saw lots of codes (especially, the anorm part) like:
父母=>
这为什么有意义?
推荐答案
您可以同时具有自类型和this
别名:
You can have a self-type and this
aliasing at the same time:
abstract class Parser[+T] { p: SomeAssumedType => … }
如果不包括类型说明,Scala将假定变量的类型是周围类的类型,从而为您提供this
的简单别名.
If you don’t include a type ascription, Scala will assume that the type of the variable is the type of the surrounding class, thus giving you a simple alias for this
.
如果您将名称保持为this
,那么Scala希望您以可以满足该命名的方式来初始化此类.
If you keep the name this
with the ascription, then Scala expects you to initialise this class in a way that the ascription can be fulfilled.
对于this
别名.在这种情况下,需要这样做:
As for the this
aliasing. Here’s the situation in which this is needed:
object OuterObject { outer =>
val member = "outer"
object InnerObject {
val member = "inner"
val ref1 = member
val ref2 = this.member
val ref3 = outer.member
def method1 = {
val member = "method"
member
}
def method2 = {
val member = "method"
this.member
}
def method3 = {
val member = "method"
outer.member
}
}
}
scala> OuterObject.InnerObject.ref1
res1: java.lang.String = inner
scala> OuterObject.InnerObject.ref2
res2: java.lang.String = inner
scala> OuterObject.InnerObject.ref3
res3: java.lang.String = outer
scala> OuterObject.InnerObject.method1
res4: java.lang.String = method
scala> OuterObject.InnerObject.method2
res5: java.lang.String = inner
scala> OuterObject.InnerObject.method3
res6: java.lang.String = outer
这篇关于斯卡拉这个别名和自我类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!