val behavior in scala REPL and Intellij

前端 未结 2 1696
小鲜肉
小鲜肉 2021-01-25 19:25

as expected reassignment is giving error like below in REPL

scala> val a=1
a: Int = 1

scala> a=2
:12: error: reassignment to val
       a=2
         


        
相关标签:
2条回答
  • 2021-01-25 19:52

    The REPL is intended for rapid friction-less experimentation. It would be very annoying if you had to restart from scratch just because you accidentally mistyped val a = 32 when you meant val a = 23.

    Therefore, the REPL is designed in such a way that it gives the appearance of breaking the rules of Scala, although it actually doesn't. The code that gets actually compiled corresponding to the code you entered looks a little bit like this:

    object line$1 {
      val a=1
    }
    
    object line$2 {
      import line$1._
      val a=2
    }
    
    0 讨论(0)
  • 2021-01-25 19:57

    From Scala docs REPL overview:

    • every line of input is compiled separately.
    • dependencies on previous lines are included by automatically generated imports.

    Combining these two facts, we can understand that they are not in the same namespace, unlike the example you provided which 2 variables called x are in the same class.

    0 讨论(0)
提交回复
热议问题