Scala Companion Objects
Introduction to Scala companion objects
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.
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}
}
class MyClass{
val id = MyClass.getNewIndex
def getIdx: Int = id
}
val cls = new MyClass
println(cls.getIdx)
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].
- Cay Horstmann,
Scala for the Impatient 1st Edition