What’s the exact deal with scope regarding variables in Scala?
When I open curly brackets I can still access the value of the outer vars (and modify them if vars):
scala> var mmm = 4
mmm: Int = 4
scala> {
| println(mmm)
| mmm += 2
| println(mmm)
| }
4
6
scala> println(mmm)
6
But Odersky says on page 180 or his book that
In a Scala program, an inner variable is said to shadow a like-named outer variable,
because the outer variable becomes invisible in the inner scope.
This seems even weirder:
scala> val a = 4
a: Int = 4
scala> {
| println(a)
| }
4
So do I get a copy of it created in the inner scope?
scala> val a = 4
a: Int = 4
scala> {
| val a = 8
| }
Why can I say val again if its immutable?
scala> val a = 4
a: Int = 4
scala> {
| println(a)
| val a = 8
| println(a)
| }
But for this one I get an error:
error: forward reference extends over definition of value a
println(a)
If you create a new one in the block, the new one shadows the old (outer) one. If you don’t, you refer to the outer one.
It doesn’t matter where in the block the new one is created; if it appears anywhere, it shadows the outer one.
So,
Edit: let’s unpack the last one