Jenkov.com
Tutorials Books About
Scala

1 Scala Tutorial
2 Scala Overview
3 Scala Classes
4 Scala Singleton and Companion Objects
5 Scala Applications
6 Scala Variables
7 Scala Data Types
8 Scala Arrays
9 Scala if
10 Scala while
11 Scala for
12 Scala Exceptions + try catch finally
13 Scala Match Expressions
14 Compiling Scala with Ant




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!