为什么可以在 REPL 中声明同名变量? [英] Why is it possible to declare variable with same name in the REPL?

查看:52
本文介绍了为什么可以在 REPL 中声明同名变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala> val hi = "Hello \"e"
hi: String = Hello "e


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

在同一个 REPL 会话中,为什么它允许我声明具有相同名称的变量 hi?

Within same REPL session why its allowing me to declare variable hi with same name ?

scala> hi
res1: String = go

scala> hi="new"
<console>:8: error: reassignment to val
   hi="new"
     ^

这个错误我知道我们不能重新分配 val

This error i understood we cannot reassign val

推荐答案

REPL 有趣的设计特点是你的两个定义被翻译成:

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
}

您可以使用 scala -Xprint:parser 来见证确切的包装策略:

You can witness the exact wrapping 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)
  }
}

这篇关于为什么可以在 REPL 中声明同名变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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