Please consider this code:
trait A {
def a : Int
}
def f ( a : Int ) = {
def a0 = a
new A {
def a = a0
}
}
The problem is quite evident: def a0 = a
is a typical annoying boilerplate code and the situation only worsens when more parameters get introduced.
I am wondering if it's possible to somehow get a direct reference to the a
variable of the outer scope inside the declaration of the instance of the trait and thus to get rid of the intermediate a0
.
Please keep in mind that changing name of input parameter of the function is not allowed as is changing the trait.
Here is an anonymous solution.
I think the closest you can get to (without changing your API) is:
In Scala, methods are not types. Thus, it is not possible to reference them with the type system or any of there members.
I don't think there is direct way to do that, because it would require some special (hypothetical) identifier
thisMethod
. However, depending on your context, the following two ways to avoid the name shadowing might be possible:(1) Replace anonymous class
A
with implementing class:(2) Define
f
in an abstract trait and use a concrete implementation for it: