1

I have the following code, and 2 situations Inside the

  1. if in the method hideVariableFromOuterBlock I am declaring a variable k which shadows the one defined in the outer block.
  2. inside the second method 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.

Claudiu
  • 1,469
  • 13
  • 21

1 Answers1

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)
}
Community
  • 1
  • 1
Vlad
  • 18,195
  • 4
  • 41
  • 71
  • The answer you mentioned, although very strong, expresses a personal opinion on why shadowing is allowed. Also, it is pretty obvious how to fix the code by copying the value into another variable/constant. – Claudiu Jun 26 '15 at 22:34