Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliasing this in scala with self =>

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.

like image 553
user2325541 Avatar asked Apr 26 '13 23:04

user2325541


1 Answers

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.

like image 81
huynhjl Avatar answered Oct 03 '22 02:10

huynhjl