Why is it possible to declare variable with same name in the REPL?

前端 未结 2 1432
既然无缘
既然无缘 2020-11-30 12:17
scala> val hi = \"Hello \\\"e\"
hi: String = Hello \"e


scala> val hi = \"go\"
hi: String = go

Within same REPL session why its allowing me

2条回答
  •  时光说笑
    2020-11-30 12:29

    The interesting design feature of the REPL is that your two definitions are translated to:

    object A {
      val greeting = "hi"
    }
    object B {
      val greeting = "bye"
    }
    

    A subsequent usage will import the last definition:

    object C {
      import B.greeting
      val message = s"$greeting, Bob."  // your code
    }
    

    You can witness the exact wrapping strategy with scala -Xprint:parser:

    object $iw extends scala.AnyRef {
      def () = {
        super.();
        ()
      };
      import $line4.$read.$iw.$iw.greeting;
      object $iw extends scala.AnyRef {
        def () = {
          super.();
          ()
        };
        val message = StringContext("", ", Bob.").s(greeting)
      }
    }
    

提交回复
热议问题