Dzhu
Dzhu

Reputation: 4381

Referencing function parameter of the same name

suppose I have a trait that has a val of the same name as a parameter of a function that is trying to create the trait instance:

def func(param: String) {
  val _param = param
  new SomeTrait {
    val param = _param
  }
}

Is there a better way to reference the function parameter 'param'?

Upvotes: 1

Views: 993

Answers (3)

Dylan
Dylan

Reputation: 13922

In your example, it makes sense to turn your SomeTrait into a class.

class SomeClass(val param: String)

def func(param: String) = new SomeClass(param)

If you can't refactor in this way, then you should simply rename the parameter:

def func(p: String) {
  new SomeTrait {
    val param = p
  }
}

Upvotes: 1

Andy Petrella
Andy Petrella

Reputation: 4345

Here is how you could do without the help of the apply method plus the companion object

trait SomeTrait {
  val param:String
}

class A {
  def func(param:String):SomeTrait = ((p:String) => new SomeTrait { val param = p })(param)
}

I've just introduced an anonymous encapsulating/abstracting function for the parameter, the I called it.

The result is just more concise and kind-of readable

Upvotes: 0

missingfaktor
missingfaktor

Reputation: 92046

I am afraid there isn't a better way. Depending on how frequently you need to initialize SomeTrait, you could write a factory method to reduce some of that boilerplate.

trait SomeTrait {
  def param: String
}

object SomeTrait {
  def apply(param: String): SomeTrait = {
    val _param = param
    new SomeTrait {
      def param = _param 
    }
  }
}

def func(param: String) = {
  SomeTrait(param)
}

Upvotes: 4

Related Questions