I would like to make the following work:
def foo(x:Int = 1) = {
object obj {
val x = foo.this.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?
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.
It is not possible in Scala.
You write the code, so the easiest option will be to rename one of the
x
s and problem solved.However, if from some reason you really need it - you can do a trick and create an
object
that will behave like your methodBecause the
apply
method is implemented you can use it as you would use a functionFoo()
No, this is not possible. There is no way to identify the outer block of the function definition.
For your syntax to work foo would have to be an object with a member x. i.e. this works:
foo
also could be a singleton object extending FunctionX, which gives you something very similar to a method. But it is probably easier to just rename one of the values.Why not just introduce a new variable that has the same value as
foo
's argumentx
, but is not shadowed?