Scala – Class vs Object

Scala class does not have static variables and methods in  it but it has a singleton object where we can define the relevant methods.

Please refer the below example.


class Hw {
  def method() {
    println("Class method");
  }
}

object Hw {
  def method() {
    println("Object method");
  }
}

object HwTest {
  def main(args: Array[String]) {
    var hw: Hw = new Hw();
    hw.method();
    Hw.method();
  }
}

Here we have a Hw class and an object with the same name. In this scenario, the singleton object Hw is called as Companion object. We can use this object just like a static method. Refer the HwTest main method and its output.

 

Capture

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s