Why is it possible to declare a variable with the same name in REPL?
scala> val hi = "Hello \"e"
hi: String = Hello "e
scala> val hi = "go"
hi: String = go
In the same REPL session, why does it allow me to declare a hi variable with the same name?
scala> hi
res1: String = go
scala> hi="new"
<console>:8: error: reassignment to val
hi="new"
^
This error I realized that we cannot reassign val
An interesting design feature of REPL is that your two definitions are translated into:
object A {
val greeting = "hi"
}
object B {
val greeting = "bye"
}
In subsequent use, the last definition will be imported:
object C {
import B.greeting
val message = s"$greeting, Bob." // your code
}
You can see the exact packaging strategy with scala -Xprint:parser:
object $iw extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
import $line4.$read.$iw.$iw.greeting;
object $iw extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
val message = StringContext("", ", Bob.").s(greeting)
}
}