I have the following code, and 2 situations Inside the
if
in the methodhideVariableFromOuterBlock
I am declaring a variablek
which shadows the one defined in the outer block.- inside the second method
hideParameterName
I am declaring a variablek
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.