In Scala, is there a way to access a symbol (varia

2020-04-02 09:15发布

问题:

For example:

def factory(_name: String) = new Person {
    val name: String = _name
}

I'm looking to avoid mangling the name of _name in the outer scope.

回答1:

While far from an ideal approach, this "does the trick":

abstract class Person { val name: String }
def factory(name: String) = {
   val _name = name
   new Person {
     val name: String = _name
   }
}
factory("Fred").name // Fred

I don't know of any other way to get close. There is a section in the Scala Language Specification (Chapter 2) which talks about shadowing -- and in no place does it discuss a way to qualify those "implicit" scopes.

Happy coding.



标签: scala