You might have already noticed something that looks like shadowing in the interpreter:
scala> val a = 1 a: Int = 1
scala> val a = 2 a: Int = 2
scala> println(a) 2
In the interpreter, you can reuse variable names to your heart's content. Among other things, this allows you to change your mind if you made a mistake when you defined a variable the first time in the interpreter. The reason you can do this is that, conceptually, the interpreter creates a new nested scope for each new statement you type in. Thus, you could visualize the previous interpreted code like this:
Thanks, you are speaking about scope. I test it in a While statement, and yes return error..in the same scope..
scala> while ( i < 3) { | val num2 = 10 | print (num2) | val num2 = 45 | i += 1; | } <console>:10: error: num2 is already defined as value num2 val num2 = 45 ^ and this other case a first definition of num1 and a change in the while statement...
scala> val num1 = 10 scala> while ( i < 3) { | print (num1) | val num1 = 30 | i += 1; | } <console>:9: error: forward reference extends over definition of value num1 print (num1) ^ but the interpreter can overwrite the definitions if they are done only in the command line....
but in the second case above, the "While" is returning error and should not... "if I follow the logic of your answer"...The sentence "while" Is in another scope? or not ??? Why the "while" return error in the second example then....??? that is a prove that the while is in the same scope or can not to overwrite the first definition seems like the first definition in the command line is a global definition....is confuse for me...yet....
I had a mistake the second error is another type of error
scala> print (i) 3 scala> i = 0 i: Int = 0
scala> while ( i < 3) { | val num1 = 40 | print (num1) | i += 1; | } 404040 scala>
I was typing "print (num1) " before the definition "val num1 ". The num1 from the "while", is not he same as the num1 definition in the command line.. all is ok for me now, thanks!
val num1 = 10 val num1 = 11 will produce a compile time error... because "val" declares an immutable value, "var" on the other hand declares a mutable value i.e variable