Visit our archive

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:

It’s a trivial example, but 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.

  • Name (Required)

  • Email (Required, but not published)

  • Url (Optional)

  • Comment (Required)