Tuesday, January 26, 2016

Learning Scala - Session 5 - Case Class & Singleton

Case class in Scala

- Creates an object without using new


package com.first

case class Person(lastname:String, firstname: String, age:Int) {

  println(s"Person is $firstname $lastname, age is $age")
}

object PersonObj extends App{

  val person1 = Person("Shree","Anita",30)
  val person2 = Person("Kumar", "Saahil", 30)
  val person3 = person1.copy(firstname="Shilpa",age=29)
}

Output

Person is Anita Shree, age is 30

Person is Saahil Kumar, age is 30
Person is Shilpa Shree, age is 29 (output)

When you declare a case class the Scala compiler does the following for you:
    • Creates a class and its companion object.
    • Implements the apply method that you can use as a factory. This lets you create instances of the class without the new keyword. E.g.:
    • Prefixes all arguments, in the parameter list, with val. This means the class is immutable, hence you get the accessors but no mutators. 
    • Adds natural implementations of hashCodeequals and toString. Since == in Scala always delegates to equals, this means that case class instances are always compared structurally
    • Generates a copy method to your class to create other instances starting from another one and keeping some arguments the same. E.g.: Create another instance keeping the lastname and changing firstname and age:
    • val person3 = person1.copy(firstname="Manu",age=29)
    • Person is Manu Shree, age is 29 (output)
    • Please refer http://www.alessandrolacava.com/blog/scala-case-classes-in-depth/ for in depth details on case class
Implementing Singleton in Scala
When you replace the keyword class by object, you define a singleton object. A singleton definition defines a new type like a class does, but only one single object of this type can be created—therefore the name "singleton".

Singleton.scala

object Singleton {

  println("Creating Singleton Object")

  

  var sum = 0;
  def add(num:Int){

    sum += num

      println(s"Sum =$sum")

  }

}



Main.scala
object Main extends App{
  Singleton.add(10)
  Singleton.add(5)
  Singleton.add(20)
}

Output
Creating Singleton Object

Sum =10

Sum =15

Sum =35



The definition will create an object of this type, and assign the name MySingleton to it. The construction of the object happens the first time the object is used (so if you define a singleton and never use it, it will not be constructed at all).

You can define both a class and a singleton object with the same name. In this case, the singleton is called the companion object of the class. A companion object is allowed to use the private fields and private methods of a class.

No comments:

Post a Comment