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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With