Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Is there a default class if no class is defined?

Tags:

scala

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 ?

like image 883
Rahul Avatar asked Sep 02 '11 06:09

Rahul


People also ask

How do classes work in Scala?

Classes in Scala are blueprints for creating objects. They can contain methods, values, variables, types, objects, traits, and classes which are collectively called members. Types, objects, and traits will be covered later in the tour.

What is the difference between Scala class and object?

Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.

What is any class in Scala?

class Any. Class Any is the root of the Scala class hierarchy. Every class in a Scala execution environment inherits directly or indirectly from this class. Starting with Scala 2.10 it is possible to directly extend Any using universal traits.

How do I create an instance of a class in Scala?

In Scala, an object of a class is created using the new keyword. The syntax of creating object in Scala is: Syntax: var obj = new Dog();


1 Answers

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.

like image 88
huynhjl Avatar answered Nov 09 '22 05:11

huynhjl