Scala Classes & Objects – Singleton Objects, Companion Classes

Filed Under: Scala

Earlier we learned about Scala Programming Language and it’s installation on Windows and *nix systems. Scala is an object oriented functional programming language, so today we will look into Scala Classes and Objects in brief.

Scala Class and Object

Classes can be defined as a static template from which many objects can be instantiated at runtime.

Let us look into an example of how to define a class in Scala;


class Student() {
 	var total:Int = 0
 	def calculateTotal(ma1:Int,ma2:Int) {
 	total = ma1 + ma2
 	}
 	override def toString(): String = "(" + total + ")";
}

Here we are defining a class named Student using the keyword “class”. We are then declaring a variable total and initializing the variable value to zero. A method calculateTotal is defined with arguments ma1 and ma2 which are the individual marks/scores of two subject. The scores are added and a grand total is calculated and stored in the “total” variable.

We are overriding the toString standard method so that when we print it, we get useful information. Below image shows how it will look in the Scala terminal.

Scala-Class-Example

Now we shall test the method by creating an object of the Student class as shown below.


object Stud1 {
	def main(args:Array[String]) {
	val totalMarks = new Student()
	totalMarks.calculateTotal(55,60)
	println("Grand Total Marks of the Student is"+totalMarks)
}
}

Stud1 is an object of the Student class. We define the main method with String type array as an argument. We create totalMarks as an instance of Student class using the new keyword and invoke the calculateTotal method passing the marks and print the total marks secured.

Please note that the main method should be defined since it is the entry point for the program execution.

Now run the above code by invoking the main method of Stud1 as


scala>Stud1.main(null)
Total Marks secured by the Student is(115)

In Scala, we will have to explicitly specify null as a parameter since it is a functional language and all functions take in parameters. Below image shows creating an object and executing it in Scala shell.

Scala-Object-Example

Extending a Class in Scala

A base class can be extended which is similar to Java except for two restrictions that only the primary constructor of child class can pass parameters to the base class constructor and override keyword must be specified.

Consider an example of overriding the base class method;


class Student(val m1:Int,val m2:Int) {
 	var total:Int = m1 + m2
	var ma1:Int = m1
	var ma2:Int = m2
 	def calculateTotal(ma1:Int,ma2:Int) {
 	total = ma1 + ma2
	println("Total is :"+total)
 	}
 	override def toString(): String = "(" + total + ")";
   }

The student is the base class which has a calculateTotal method accepting marks of two subjects and output the total marks.

Scala-inheritance-base-class

Now we shall create a subclass extending the Student class which adds the marks of four subjects and calculate the grand total as shown below.


class CollegeStudent(override val m1:Int,override val m2:Int,val m3:Int,val m4:Int) extends Student(m1,m2) {
	var ma3:Int = m3
	var ma4:Int = m4
	var tot:Int = 0;
 	def calculateTotal( ma1:Int, ma2:Int, ma3:Int,  ma4:Int) {
	tot = ma1 + ma2 + ma3+ ma4
	println("Total is :"+tot)
	}
	override def toString():String = "(" + tot + ")";
}

We are adding “override” keyword to variables m1 and m2. The keyword “extends” is used to extend the base class Student. But the method is not overridden since the implementation has a different definition.

Scala-inheritance-child-class

Create an object ColStud of CollegeStudent class as;


object ColStud {
def main(args:Array[String]) {
val total = new CollegeStudent(72,65,85,60);
total.calculateTotal(72,65,85,60);
println("Grand Total Marks of the Student is"+total)
}
}

Run the above code by executing the below command;


scala> ColStud.main(null)
Total is :282
Grand Total Marks of the Student is(282)

Scala-Inheritance-execute

Singleton Objects in Scala

There is no static keyword in Scala, instead we have singleton objects. All we need is to use object keyword to create a singleton object. We can call it’s methods directly, we can’t pass parameters to its primary constructor. Below is a quick example of singleton objects in Scala.


object Test{
    def say(){
    println("Hi")
  }
}

Below image shows how to execute the above-defined method, notice how similar it is to Java static method execution.

Scala-singleton-object

Inbuilt objects in Scala library

There are many inbuilt objects in scala library one among them is the Console object which reads the values and prints on the terminal.

Lets consider an example for Console object;


object Cons {
def main(args:Array[String]) = {
    Console.println("Enter a number :");
    val num = Console.readInt;
    Console.println("Entered Number is :"+num)
    }
}

We are creating a Cons object. In the main method, we ask the user to enter a number and read the entered number from the terminal using readInt and print the entered number.

Run the code as shown below


>Cons.main(null)
Enter a number :
Entered Number is :345

Scala -deprecation mode

Below image shows what happens when we define Cons object in Scala shell.

Scala-Console-Object

Notice the warning “there was one deprecation warning; re-run with -deprecation for details”. It doesn’t tell us which line number is causing this warning, however, the object is defined. But using deprecated methods is not a good idea. So we can run Scala shell with -deprecation option and it can provide useful information to correct it. Below image shows it in action.

Scala-deprecation-Console-Object

Companion Classes and Objects in Scala

An object which has the same name as that of the class object is a companion object and the class is called a companion class. For example;


class Student(sid:Int, sname:String){
val Id = sid
val name = sname
 
override def toString() =
this.Id+" "+" , "+this.name
}

Here we are creating a class Student with sid and sname as parameters and displaying these parameters.

Scala-Companion-Class-Object-1

Create the object with the same name Student with displayDetails method where we will print the details of the student. This Student object is termed as companion object since it has the same name as of the class and the Student class is termed as Companion class.


object Student{
def displaydetails(st: Student){
println("Student Details: " + st.Id+","+st.name);
}
}

Scala-Companion-Class-Object-2

Now create the testStud object to invoke the methods of these companion object and class as below;


object testStud {
 
def main(args: Array[String]) = {
    
var st = new Student(21,"Peter")
println(st)
    
Student.displaydetails(st)
}
}

Here we are printing the student object and invoking the displaydetails method by passing the student object st.

Run the above code as testStud.main(null) which produces the following output;


scala> testStud.main(null)
21  , Peter
Student Details: 21,Peter

Scala-Companion-Class-Object-3

If you look at the above images, you will notice warning as “previously defined class Student is not a companion to object Student. Companions must be defined together; you may wish to use :paste mode for this.”

Notice that it’s suggesting to use paste mode, below image shows how to use paste mode to avoid this warning.

Scala-shell-paste-mode

Scala Compiler

Before I conclude this post, I want to show you how to compile and run a class in Scala. If you notice above images, I am using Scala shell to create classes and use it, but my code will be lost as soon as I close it. So we can save Scala program in a file with .scala extension and then compile and run it.

Test.scala


object Test{
	def main(args: Array[String]) = {
	println("Welcome to JournalDev!")
	}
}

It’s very similar to compiling and running a class in Java, as shown in below shell execution code.


Pankaj:~ pankaj$ scalac Test.scala 
Pankaj:~ pankaj$ scala Test
Welcome to JournalDev!

You will notice a file named Test.class created when you compile the Test class. Since Scala is entirely an object-oriented language, we will explain more concepts in the future articles.

Comments

  1. MELWIN LOBO says:

    Are the parameter values needed in the line below? They are present on the line after also.

    val total = new CollegeStudent(72,65,85,60);

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages