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.

user2325541
  • 101
  • 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. – adelbertc Apr 26 '13 at 23:48
  • 1
    Is the `self` alias for `this` visible to derived types? If so, perhaps there's a dependency on it somewhere else in the library? – Richard Sitze Apr 27 '13 at 00:18

1 Answers1

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.

huynhjl
  • 41,520
  • 14
  • 105
  • 158
  • 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. – sourcedelica Apr 29 '13 at 14:48
  • @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... – huynhjl Apr 30 '13 at 05:45
  • Thanks - I would recommend that OP asks the question on `scala-user`. – sourcedelica Apr 30 '13 at 11:34