Val 在 Scala 中的行为 [英] behaviours of Val in Scala

查看:40
本文介绍了Val 在 Scala 中的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从 Eclipse 执行以下代码时出现错误,因为我无法重新分配 Val,对吗?

对象测试{def main(args: Array[String]){val tempVal = 100;val checkval = if (tempVal > 50) 1 else 0println("新值是:" + checkval);//下面出现错误checkval1 = if (tempVal > 200) 0}}

现在,当我尝试从命令行执行相同操作时,为什么我没有收到相同的错误?

解决方案

在 REPL 中,您键入的每个语句都将被包装在一个对象中,该对象嵌套在前一个语句的对象中.这是专门完成的,以便您以后可以更改" vals 或 classes 或 traits 的值.否则,每次输入错误时,您都必须重新启动 REPL 并重新键入每个语句.

因此,您的 REPL 会话(大致)编译为如下所示:

object Line1 {值 x = 100打印(x)对象 Line2 {val y = if (x <50) 1 else 0打印(y)对象 Line3 {val y = if (x <50) 0 else 1打印(y)}val _ = Line3//强制创建 Line3 对象}val _ = Line2//强制创建 Line2 对象}val _ = Line1//强制创建 Line1 对象

由于Scala有嵌套作用域,Line3y可以覆盖Line2y.>

I am getting the error when trying to execute the below code from Eclipse because I can't reassign Val, right?

object Test {
    def main(args: Array[String]){
      val tempVal = 100;

      val checkval = if (tempVal > 50) 1 else 0

      println("The new value is: " + checkval);

      //Getting Error Below
      checkval1 = if (tempVal > 200) 0

    }
}

Now when I am trying to do the same thing from command line, why I am not getting the same error?

解决方案

In the REPL, every statement you type will be wrapped inside of an object which is nested inside the object of the previous statement. This is done specifically so that you can "change" the value of vals or classes or traits later. Otherwise you would have to restart the REPL and retype every statement everytime you make a typo.

So, your REPL session is (roughly) compiled to something like this:

object Line1 {
  val x = 100
  println(x)

  object Line2 {
    val y = if (x < 50) 1 else 0
    println(y)

    object Line3 {
      val y = if (x < 50) 0 else 1
      println(y)
    }
    val _ = Line3 // force creating the Line3 object
  }
  val _ = Line2 // force creating the Line2 object
}
val _ = Line1 // force creating the Line1 object

Since Scala has nested scopes, Line3's y can shadow Line2's y.

这篇关于Val 在 Scala 中的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆