1

Programming in Scala says:

You can [reuse variable names in the interpreter] because conceptually the interpreter creates a new nested scope for each new statement you type in.

Besides allowing to reuse variable names, does this nesting of scopes create any other difference in how the program is understood? In other words, if I don't reuse variable names, would the same scala program always be executed identically in the interactive interpreter and if run as a script?

1 Answer 1

1

No, the script runner wraps your code as local to a synthetic "main" method. The REPL wraps each line in a separate class instance or singleton object which is imported into subsequent lines as necessary.

Use -Xprint:parser,typer, or // show in REPL.

$ scala -nc -Xprint:parser,typer h.scala
[[syntax trees at end of                    parser]] // h.scala
package <empty> {
  object Main extends scala.AnyRef {
    def <init>() = {
      super.<init>();
      ()
    };
    def main(args: Array[String]): scala.Unit = {
      final class $anon extends scala.AnyRef {
        def <init>() = {
          super.<init>();
          ()
        };
        println("hello, world")
      };
      new $anon()
    }
  }
}

compare to:

$ scala -Xprint:parser
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_111).
Type in expressions for evaluation. Or try :help.

scala> println("hello, world.")
[[syntax trees at end of                    parser]] // <console>
package $line3 {
  object $read extends scala.AnyRef {
    def <init>() = {
      super.<init>();
      ()
    };
    object $iw extends scala.AnyRef {
      def <init>() = {
        super.<init>();
        ()
      };
      object $iw extends scala.AnyRef {
        def <init>() = {
          super.<init>();
          ()
        };
        val res0 = println("hello, world.")
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.