Monday 28 May 2018

Object in Scala

In Scala, objects are a singleton. Scala doesn’t have static class members (variables or methods). Instead, it has singleton objects.

Simple example of object:

object Person

As an object is a singleton, it does not have constructor  parameters.

Ex –

object Person(age: Int){} // Error
object Person(){} // Error
object Person{} // Success

object Person{
  val age : Int = 10
  var name : String = "Prashant"
  def bmi(height:Int, weight:Int) = weight/height
}

Above object has two parameters and one method. We can relate these parameters as static parameters in a java.

To call a method from the object, we don't need instance as doesn't require new keyword, we can call  method like "Person.bmi".

An object with the same class name in one file called companion object.
We can define apply(), unapply() and update() methods in an Object.

apply method is a special method in Scala. when we do obj(parameter), Scala calls obj.apply(parameter)

object Person {
   def apply() = {
    println("zero argument apply function")
  }

  def apply(a: Int, b: String) = {
    println("Two argument apply function")
  }

  def update(a: Int) = {
    println("Update : a : [" + a + "]")
  }

  def update(a: Int, b: Int, c: String) = {
    println("Update : a : [" + a + "] : [b] : [" + b + "] : [c] : [" + c + "]")
  }

}


object Client extends App { 
  Person
  Person()
  Person(1, "Hi..")
  Person() = 2
  Person(4, 5) = "Hello.."
}

Output :
zero argument apply function
Two argument apply function
Update : a : [2]
Update : a : [4] : [b] : [5] : [c] : [Hello..]

We can use apply method in a companion object as a Factory/builder.

Ex:
abstract class DatabaseDriver {
  // some database stuff
}

object DatabaseDriver {
  def apply(config: Configuration) = config.dbType match {
    case "MYSQL" => new MySqlDriver()
    case "PSQL" => new PostgresDriver()
    case _ => new GenericDriver()
  }
}

val mydatabase = DatabaseDriver(dbConfig)

internally it will call

val mydatabase = DatabaseDriver.apply(dbConfig)

We can override apply method several times, to get the different behavior.

No comments:

Post a Comment