Java How To's and Utilities
Scala Introduction
Scala Overview
 
Scala Classes
Scala Singleton + Companion Objects
Scala Applications
Scala Variables - var + val
Scala Data Types (Int, String etc.)
Scala Arrays
Scala if
Scala while
Scala for
Scala Exceptions + try catch finally
Scala Match
 
Compiling Scala with Ant
 


Scala Singleton and Companion Objects

Connect with me:  
  Jenkov.com - News

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

NextNext : Scala Applications

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