Over a million developers have joined DZone.

Brief Overview of an "Object" in Scala

In the Java world we are all familiar with the term object and interchangeably use it with the term instance. However, they could not be more different in Scala.

· Java Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

In the Java world we are all familiar with the term object and interchangeably use it with the term instance. Both these terms represent initialization of a class with the required parameters. But the same cannot be applied in Scala, because in Scala “object” is a keyword and represents a totally different but somewhat related concept. It's totally different because “object” keyword represents a single instance of that with which it is used. And similar because it still represents some instance.

I have divided the post into different sections namely:

  1. Simple example of object
  2. An example of inbuilt object in Scala library
  3. Companion classes and Companion objects
  4. Companion object with apply method

Simple example of “object”

object SimpleObject{
  val param1 : Int = 10
  var param2 : String = "Yes"

  def method1 = "Method 1"

  def sum(a:Int, b:Int) = a + b
object Main {

  def main(args: Array[String]) = {



    SimpleObject.param2 = "No"



    println(SimpleObject.sum(10, 15));



In the above object- SimpleObject we have declared 2 parameters and 2 methods. To know the different between var and val please read val versus var in scala. TheSimpleObject object is used in another object Main which declares the main method. TheMain object containing the main is the starting point of the application. People from the Java world will immediately relate the use of the SimpleObject to the static members in Java. I will touch upon that concept as well towards the end of the post when I explain about Companion classes.

An important feature of an object in Scala is that it is Singleton i.e there is only one instance. And you cannot even use the new operator to create another instance.

An example of inbuilt object in Scala library

There are numerous examples of object‘s in Scala API and one among them is theConsole object which

Implements functionality for printing Scala values on the terminal as well as reading specific values. Also defines constants for marking up text on ANSI terminals.

Lets look at an example of using Console object:

object Main {

  def main(args: Array[String]) = {
    Console.println("Enter some string: ");

    val input = Console.readLine;

    Console.println("The string entered is: "+input)



Companion classes and Companion objects

By now you have an brief idea of what an object is. Now lets see yet another concept associated with object called the Companion classes/Companion objects. When we have an object with same name as that of the class then we say that the object is aCompanion object and the class is companion class. In addition to having the same name, they should be part of the same package and be defined in the same file.

The below code shows the Companion objects in action:

object Main {

  def main(args: Array[String]) = {

    var emp = new Employee(123,"Sana", "Blore")
    println(emp)//123 Sana, Blore
    Employee.saveToDb(emp)//Saving: Sana to db


//Companion class
class Employee(id:Int, n:String, p: String){
  val empId = id
  val name = n
  val place = p

  override def toString() = 
    this.empId+" "+this.name+", "+this.place

//Companion object
object Employee{
  def saveToDb(emp: Employee){
    println("Saving: " + emp.name+" to db");

In the above code we have an Employee class and an associated companion object. The companion object defines a method called saveToDb. In the same code I have shown how the companion class and companion object are used. The method saveToDb exhibits behaviour similar to that of the statics in Java. In scala there is no concept of “static” members, the same functionality is provided by the companion object.

Looking at the same example in Java we would have:

public class StaticSample {

  public static void main(String[] args){
    Employee emp = new Employee(123, "Sana", "Blore");
    System.out.println(emp);//123 Sana, Blore

    //Accessing the static method using the object.
    emp.saveToDb(emp);//Saving employee: Sana

    //Accessing the static method using class name.
    Employee.saveToDb(emp);//Saving employee: Sana


class Employee{
  String name;
  String place;
  int id;
  public Employee(int id, String name, String place) {
   this.id = id;
   this.name = name;
   this.place = place;
  public String toString(){
    return this.id+" "+this.name+", "+this.place;
  public static void saveToDb(Employee emp){
    System.out.println("Saving employee: "+emp.name);

One can notice that in Java the static members can be accessed both using the instance and the class name, which can be quite confusing. But the same is not possible in Scala because the only way to access the members in the companion object is to use the companion object and not the instance of the companion class.

Companion class/object in Scala API

In Scala API there are numerous places where concept of companion object is leverage and one such usage is the Array class. The companion object for Array class consists of methods like applycopyempty among others.

Companion object with apply method

Lets consider the Employee example from above and add an apply method to it. The use of apply method is that it provides a way to create instances of the companion class without using the new operator directly and instead use the object literal syntax to create the instance of the companion class. Lets look at the sample code:

//replace this with the use of new operator above.
var emp = Employee(123,"Sana", "Blore")

object Employee{
  //Rest of the definition is as above.
  def apply(id: Int, name: String, place: String) =
    new Employee(id, name, place)

The apply method can be used to create Factories for creating instances of the companion class.

In the Scala API Array class contains apply method which enables us to create arrays like:

var arr1 = Array(1,2,3,4,5)
var arr2 = Array("a","b","c")    

This was in brief about object in Scala.

Building Identity Management, including authentication and authorization? Try Stormpath! Our REST API and robust Java SDK support can eliminate your security risk and can be implemented in minutes. Sign up, and never build auth again!


Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}