简体   繁体   中英

In Scala, is there a way to access a symbol (variable) defined in an outer scope?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM