Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Ambiguous Variable Name Within A Method

I've seen some questions regarding Scala and variable scoping (such as Scala variable scoping question)

However, I'm having trouble getting my particular use-case to work.

Let's say I have a trait called Repo:

trait Repo {
    val source: String
}

And then I have a method to create an implementation of Repo...

def createRepo(source: String) = 
  new Repo {
    val source: String = source
  }

Of course I have two source variables in use, one at the method level and one inside of the Repo implementation. How can I refer to the method-level source from within my Repo definition?

Thanks!

like image 263
shj Avatar asked Jul 16 '26 16:07

shj


1 Answers

Not sure if this is the canonical way, but it works:

def createRepo(source: String) = {
  val sourceArg = source
  new Repo {
    val source = sourceArg
  }
}

Or, you could just give your paramenter a different name that doesn't clash.

Or, make a factory:

object Repo {
  def apply(src: String) = new Repo { val source = src }
}

def createRepo(source: String) = Repo(source)
like image 137
Luigi Plinge Avatar answered Jul 19 '26 20:07

Luigi Plinge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!