val behavior in scala REPL and Intellij

五迷三道 提交于 2021-02-05 08:49:06

问题


as expected reassignment is giving error like below in REPL

scala> val a=1
a: Int = 1

scala> a=2
<console>:12: error: reassignment to val
       a=2
        ^

But the below reassignment is not giving error in REPL when a=2 preceded with val.

scala> val a=1
a: Int = 1

scala> val a=2
a: Int = 2

When I execute the below code in Intellij its giving error.

object Test {
  def main(args: Array[String]) {
    val x = 1
    val x = 2
  }
}

Why val a=1 and val a=2 are not giving any error in REPL(error if it is only a=2) but error in Intellij.


回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/64667388/val-behavior-in-scala-repl-and-intellij

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!