Brief overview of An “object” in Scala

In 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. Its 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]) = {
    
    println(SimpleObject.param1)
    
    println(SimpleObject.param2)
    
    SimpleObject.param2 = "No"
      
    println(SimpleObject.param2)
    
    println(SimpleObject.method1)
    
    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. The SimpleObject object is used in another object Main which declares the main method. The Main 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 the Console 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 a Companion 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 apply, copy, empty 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.

Some of the recommended books for learning Scala:

1 thought on “Brief overview of An “object” in Scala”

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading