Scala Snippet: Object, Companion Object and Static Methods
If you are a Java developer moving to Scala, one notable difference in terminology that can cause confusion is the term 'object'. In Java an object is always an instance of a class, created by calling a constructor.
Object
In Scala an object is used for defining a single instance of a class with the features you want. In practice this means you will use it:
- to keep utility/helper methods and constants in one place
- to have a single immutable instance to share across a system
- to implement the singleton design pattern to coordinate actions across a system
An object can have the same features as a class. You can extend other classes or traits. The only notable difference is that an object cannot have constructor parameters.
Companion Object
In Java there might be occassions where you want to use static methods. In Scala you define these methods inside a 'companion object', which has to be defined in the same source file as the class. The class and object can access each others private methods and variables, but you have to do it as you would call a out of scope static method in Java. Checkout this example in the repl:
$ scala
Welcome to Scala version 2.11.4 (Java HotSpot(TM) Client VM, Java 1.7.0\_75).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
object Camera {
def updateShutterCount(shutterCount:Long): Long = {
var updatedShutter = shutterCount + 1;
updatedShutter
}
}
class Camera(brandName:String, modelName:String) {
val brand = brandName;
val model = modelName;
var shutterCount: Long = 0;
def makePicture {
shutterCount = Camera.updateShutterCount(shutterCount)
}
}
// Exiting paste mode, now interpreting.
defined object Camera
defined class Camera
scala> val canon = new Camera("Canon", "5D mark III")
canon: Camera = Camera@17403a7
scala> canon.shutterCount
res0: Long = 0
scala> canon.makePicture
scala> canon.shutterCount
res2: Long = 1
As you can see, I've used the "static" method from the companion object to update the shuttercount when calling the makePicture method on my canon Camera. Finally, a singleton object that does not share the same name with a companion class is called a standalone object. original article