I often come across a situation where I have a factory method for some attribute, and the argument names conflict with the elements of the attribute, causing them to be hidden:
trait MyTrait { val a: Int val b: String } object MyTrait { def apply(a: Int, b: String): MyTrait = new MyTrait { val a = a
So usually I need to do something ugly, like:
def apply(aA: Int, bB: String): MyTrait = new MyTrait { val a = aA val b = bB }
or make local copies of the arguments:
def apply(a: Int, b: String): MyTrait = { val localA = a val localB = b new MyTrait { val a = localA val b = localB }
I would like the parameters of the apply method to be the same as the elements of my attribute, so that the client code reads well when I use named parameters: for example. MyTrait(a=3,b="123") .
Is there a mechanism that allows me to capture the outer region where the argument parameters are defined, but the anonymous class does not yet exist? For example, something like:
def apply(a: Int, b: String): MyTrait = { outer => new MyTrait { val a = outer.a val b = outer.b } }
Thanks!
source share