Is there a way to reference a function parameter that is shadowed by an inline class field?

Viewed 54

Is there a way to reference a shadowed parameter without resorting to naming the parameter _name or re-binding the parameter before the instantiation?

trait Stuff {
  def name: String
}
...
def create (name: String): Stuff = new Stuff {
  // this doesn't work since it references itself
  // how do I make the rhs refer to the parameter, 
  // not the method on the class?
  override def name = name
}

I would prefer to keep the name of the parameter the same, since callers will prob use named parameters. Re-binding would work, but that's a lot of repetition if there are a lot parameters.

1 Answers

This isn't a direct solution to the question, but this is perhaps a more typical pattern for creating objects in Scala:

class NamedStuff(name: String) extends Stuff

def create(name: String): Stuff = new NamedStuff(name)

Note that the name parameter to NamedStuff automatically overrides the name method in Stuff.

Related