Overview

Scala does not support static functions. We saw that object classes can be used to implement patterns like the singleton pattern. Moreover, often it make more sense that a function is a class function. We can do this using companion objects.

Companion objects

A companion object has the same name as the class it refers to. It is implemented using the object keyword

object MyClass{
    
    private var currentIndex = 0
    def getNewIndex : Int = {currentIndex +=1; currentIndex}
}
defined object MyClass
class MyClass{
    val id = MyClass.getNewIndex
    def getIdx: Int = id
}
defined class MyClass
val cls = new MyClass
println(cls.getIdx)
1
cls: MyClass = ammonite.$sess.cmd5$Helper$MyClass@38c61f45

Both the class and its companion object can access each other’s private features. Furthermore, they must be located in the same source file [1].

Note that the companion object of a class is accessible, but it is not in scope [1]. This means that in the example above we need to use MyClass.getNewIndex and not just getNewIndex to invoke the method of the companion object [1].

References

  1. Cay Horstmann, Scala for the Impatient 1st Edition