在 Scala 中,有没有办法访问在外部作用域中定义的符号(变量)?

在 Scala 中,有没有办法访问在外部作用域中定义的符号(变量)?

问题描述:

例如:

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

我希望避免在外部范围内修改 _name 的名称.

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

虽然远非理想的方法,但这行之有效":

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

我不知道还有什么其他方法可以接近.Scala 语言规范(第 2 章)讨论了遮蔽——它没有任何地方讨论限定那些隐式"作用域的方法.

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.

快乐编码.