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();

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.




Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s