Scala Singleton and Companion Objects
Jakob Jenkov |
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();
| Tweet | |
Jakob Jenkov | |











