在 Scala 中,有没有办法访问在外部作用域中定义的符号(变量)? [英] In Scala, is there a way to access a symbol (variable) defined in an outer scope?
本文介绍了在 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.
快乐编码.
这篇关于在 Scala 中,有没有办法访问在外部作用域中定义的符号(变量)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文