Scala:如何从一个对象访问一个阴影函数变量
问题描述:
我想做以下工作:
I would like to make the following work:
def foo(x:Int = 1) = {
object obj {
val x = foo.this.x
}
}
但我不知道如何从对象中引用x。这可以在没有重新命名x的情况下完成吗?
But I don't know how to reference x from within the object. Can this be done without renaming x in one of the two spots?
重命名变量可能并不容易,例如 foo
Renaming the variables may not be easy when, for example, foo
is a widely used API function with x as a named variable, while obj
extends a 3rd party trait that has x
as an abstract member.
答
为什么不引入一个与 foo 的参数 x
,但没有影子?
Why not just introduce a new variable that has the same value as foo
's argument x
, but is not shadowed?
def foo(x: Int): Unit = {
val foo_x = x
object obj {
val x = 13
def doStuff: Unit = printf("%d %d\n", x, foo_x);
}
obj.doStuff
}
foo(42)