val hi = "go" h...">

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

+4
source share
2 answers

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)
  }
}
+10
source

, "" REPL, hi. , REPL, , , .

error: x is already defined as value x scalac.

class Foo{
  val x = "foo"
  val x = "foo"
}

val, . , .

+2

Source: https://habr.com/ru/post/1534327/


All Articles