问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/16246531/aliasing-this-in-scala-with-self