Scala Classes, Objects & Singleton Objects

Previously we have learned about Scala Programming Language, Variable Declaration and Method Declaration. Now we’ll have a closer look at the Scala classes and Objects. We’ll also learn about creating Singleton objects in Scala.

Similar to Java, classes in Scala describes the objects. Classes may contain reference variables, methods as well as constructors.
Lets have various examples of classes in Scala,

class Point(x: Int, y: Int) {
  def printPoint() = println("("+x+","+y+")")
}

// Usage
val p = new Point(1, 1)
p.printPoint
//Output
//(1,1)

In case you want to write any code in constructor, you can write in block of class after class declaration statement.

class Point(x: Int, y: Int) {
  //---------- Code of Constructor --------------
  if(x < 0 || y < 0)
    throw new IllegalArgumentException("Co ordinates can't be negative")
  //---------- Code of Constructor --------------
  def printPoint() = println("("+x+","+y+")")
}

// Usage
val p = new Point(1, -1) //This will throw IllegalArgumentException

You can also define multiple constructors using this keyword.

class Point(x: Int, y: Int) {
  //---------- Code of Constructor --------------
  if(x < 0 || y < 0)
    throw new IllegalArgumentException("Coordinates can't be negative")
  //---------- Code of Constructor --------------
  
  def this() = this(0, 0) // Constructor for Origin Point 
  def printPoint() = println("("+x+","+y+")")
}

// Usage
val p = new Point
p.printPoint
//Output
//(0,0)

Singleton object

Singleton objects are objects which has one and only one instance. In Scala, you cannot have static variable or methods in your class. Instead of defining methods or variables static, you can create a singleton object by defining methods and variables using object keyword.

//Singleton object for printing usage information
object Point {
  def usage = println("Create Origin using : new Point")
}

Point.usage
//Output
//Create Origin using : new Point

If you have observed in above examples the class name and object (singleton) name are same. Such classes are referred as Companion Classes and objects are referred as Companion objects.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>