Aliasing this in scala with self =>
Asked Answered
M

1

10

Some Scala APIs alias this to self, for example,

trait Function1[-T1, +R] extends AnyRef { self =>

I know how this aliasing works in general, but don't see how traits such as Function1 benefit from it. Function1 does not use self anywhere in its definition except for the initial mention, so what is its purpose here?

Variants of this question have been asked previously, but the answers are not directly applicable. Answers have discussed self types and inner classes, but I don't see how that applies here.

Mchale answered 26/4, 2013 at 23:14 Comment(2)
It may be done so that you can still access the this in the outer scope if Function1 is wrapped inside another class/trait.Inhospitable
Is the self alias for this visible to derived types? If so, perhaps there's a dependency on it somewhere else in the library?Assassin
R
10

See https://github.com/scala/scala/blob/2.10.1/src/library/scala/Function1.scala#L8 where it says

 // GENERATED CODE: DO NOT EDIT. See scala.Function0 for timestamp.

The code is generated by the same generator for Function0 through Function22. Somehow when it goes to Function5 you start seeing self being used:

self.apply(x1, x2, x3, x4, x5)).curried

So I suspect it was easier to have self => always included in the generator template.

Here is the commit that adds the self reference. The commit message actually explains why it does something different for n >= 5, I quote:

FunctionN, where N > 4, many fewer classes are created statically at the expense of creating more objects dynamically (which seems reasonable given how common such functions are likely to be). This also allows for curry in FunctionN for N > 8 without running into the filename length restriction.

Royall answered 27/4, 2013 at 1:37 Comment(3)
What is the difference between self.apply(x1, x2, x3, x4, x5)).curried and apply(x1, x2, x3, x4, x5)).curried? Doing a quick test they appear to work identically. So it seems like the OP question is still unanswered.Interflow
@sourcedelica, yeah, I did additional code archeology by searching the mailing list archive and the issue tracker, but could not find anything. I even downloaded 2.7.2 but it also works there without self. Beyond digging out that self is referenced in Function5 to Function22, I don't have any explanation other than it being done for readability purpose or just in case...Royall
Thanks - I would recommend that OP asks the question on scala-user.Interflow

© 2022 - 2024 — McMap. All rights reserved.