Jenkov.com
Tutorials About




Scala Singleton and Companion Objects


Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object.

A singleton object is declared using the object keyword. Here is an example:

object Main {
    def sayHi() {
        println("Hi!");
    }
}

This example defines a singleton object called Main. You can call the method sayHi() like this:

Main.sayHi();

Notice how you write the full name of the object before the method name. No object is instantiated. It is like calling a static method in Java, except you are calling the method on a singleton object instead.

Companion Objects

When a singleton object is named the same as a class, it is called a companion object. A companion object must be defined inside the same source file as the class. Here is an example:

class Main {
    def sayHelloWorld() {
        println("Hello World");
    }
}

object Main {
    def sayHi() {
        println("Hi!");
    }
}

In this class you can both instantiate Main and call sayHelloWorld() or call the sayHi() method on the companion object directly, like this:

var aMain : Main = new Main();
aMain.sayHelloWorld();

Main.sayHi();


Connect with me: Newsletter - Get all my free tips!
     



Close TOC
This website uses cookies to improve the user experience and gather statistics. Our advertisers use cookies too (3rd party cookies), to provide more relevant ads. Continued use of this website implies that you accept the use of cookies on this website. We do not share our cookies with our advertisers, and our advertisers do not share cookies with us.
OK