I have the following code, and 2 situations Inside the
if
in the method hideVariableFromOuterBlock
I am declaring a
variable k
which shadows the one defined in the outer
block.hideParameterName
I am declaring a variable k
which shadows the parameter with the same name.object Test extends App {
def hideVariableFromOuterBlock() = {
var k = 2457
if (k % 2 != 0) {
var k = 47
println(k) // this prints 47
//println(outer k)
}
println(k) // - this prints 2457 as expected
}
def hideParameterName(k: Int) = {
var k = 47
println(k) // this prints 47
//println(parameter k)
}
hideVariableFromOuterBlock()
hideParameterName(2457)
}
Is there any way in the blocks where I have shadowed the variable or parameter k
to access the shadowed value (the variable from the outer block)?
I am aware that this is not a good practice, and I will never do that. I am asking the question for educational purposes.
I did a bit of research and failed to find a clear explanation. I could clearly find/see that shadowing occurs, but found no clear explanation that the variable from the outer block can't be accessed anymore.
I am newbie in Scala.
答案 0 :(得分:1)
This answer talks about why shadowing is allowed in the first place.
As for a way to access the shadowed value, the simplest thing to do as far as I know is to rename the inner variable and the problem goes away. I suppose, for the sake of the exercise, if you really don't want to rename anything, you could assign the outer variable to a new one with a different name.
var k = 2457
val outer_k = k
if (k % 2 != 0) {
var k = 47
println(k) // this prints 47
println(outer_k)
}