Scala this alias and type

Is there any connection between this aliasing and self type ? Is this aliasing special case of self type ? In programming at scala 2nd P776, the author said:

the abstract class Parser [+ T] extends ... {p =>

You saw syntax like this in Section 29.4, where it was used to give self type to trait.

but the syntax for type self does not look like this:

this: SomeAssumedType =>

And one more question: why is this aliasing useful? I don’t see the point of giving this reference to an alias because it is already a normal alias for the current object reference, however, I saw a lot of codes in the source code of the Play platform (especially the part of the anoma), for example

sign RowParser [+ A] extends (Row => SqlResult [A]) {

parent =>

Why does that make sense?

+4
source share
1 answer

You can have type smoothing and this at the same time:

 abstract class Parser[+T] { p: SomeAssumedType => … } 

If you did not specify a record type, Scala will assume that the variable type is the type of the surrounding class, giving you a simple alias for this .

If you save the name this with agitation, then Scala expects you to initialize this class so that the label can execute.

How to smooth this . Here is the situation in which this is necessary:

 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 
+4
source

Source: https://habr.com/ru/post/1415405/


All Articles