Search code examples
scala

Scala variable resolution: class vs local variable


Why do I get an error in this code:

class A {
  val x = 0

  def foo(): Unit = {
    println(x) // Error: x is a forward reference extending over the definition of x
    val x = 0
    println(x)
  }
}

Why not the x in the first println(x) resolve to the class x? Are the local variables kind of hoisted for the whole local scope?


Solution

  • SLS (Scala Language Specification) says, at https://scala-lang.org/files/archive/spec/3.4/04-basic-definitions.html ,

    The scope of a name introduced by a definition is the whole statement sequence containing the definition. However, there is a restriction on forward references in blocks [...]

    So this seems to be working as designed, but it isn't clear to me why it's specified this way. Why "the whole statement sequence" rather than "the following statements"?