15

According to this, Scala methods belong to a class. However, if I define a method in REPL or in a script that I then execute using scala, what class does the method belong to ?

scala> def hoho(str:String) = {println("hoho " + str)}
hoho: (str: String)Unit

scala> hoho("rahul")
hoho rahul

In this example, what class does the method belong to ?

Rahul
  • 12,886
  • 13
  • 57
  • 62

1 Answers1

19

The REPL wraps all your statements (actually rewrites your statements) in objects automagically. You can see it in action if you print the intermediate code by using the -Xprint:typer option:

scala> def hoho(str:String) = {println("hoho " + str)}
[[syntax trees at end of typer]]// Scala source: <console>
package $line1 {
  final object $read extends java.lang.Object with ScalaObject {
    def this(): object $line1.$read = {
      $read.super.this();
      ()
    };
    final object $iw extends java.lang.Object with ScalaObject {
      def this(): object $line1.$read.$iw = {
        $iw.super.this();
        ()
      };
      final object $iw extends java.lang.Object with ScalaObject {
        def this(): object $line1.$read.$iw.$iw = {
          $iw.super.this();
          ()
        };
        def hoho(str: String): Unit = scala.this.Predef.println("hoho ".+(str))
      }
    }
  }
}

So your method hoho is really $line1.$read.$iw.$iw.hoho. Then when you use hoho("foo") later on, it'll rewrite to add the package and outer objects.

Additional notes: for scripts, -Xprint:typer (-Xprint:parser) reveals that the code is wrapped inside a code block in the main(args:Array[String]) of an object Main. You have access to the arguments as args or argv.

huynhjl
  • 41,520
  • 14
  • 105
  • 158
  • 1
    Thanks. Does the same happen if I were to save the method definition in a .scala script and execute it using scala ? – Rahul Sep 02 '11 at 07:55
  • @Rahul, I've added the info for script, the mechanism is different. – huynhjl Sep 02 '11 at 14:07