Case Class & Companion Object

A Class coupled with its Companion Object can be used to implement Factory Pattern. Let us checkout a use case without Case Class
scala> :paste
// Entering paste mode (ctrl-D to finish)

// c116 -> a15
//== Understanding Companion object ================

// **Here 'object DbConnector' is a Companion object for
// 'class DbConnector'
class DbConnector {
  val url = "jdbc://..."
  val db = "mydb"
  val user = "myusername"
  val pwd = "mypwd"
  def connect()  = { println ("Connecting to DB...") }
}

object DbConnector {
  def apply() = new DbConnector()
}

// ** Note here we are not using new() to create
// an object for 'class DbConnector'. This is an
// example of Factor pattern
val conn = DbConnector()

// Exiting paste mode, now interpreting.

defined class DbConnector
defined module DbConnector
conn: DbConnector = DbConnector@208279af

scala> conn.connect()
Connecting to DB...
A Case class simplifies this process further. The Scala compiler provides Companion object without the need for us to explicitly providing the Companion object
scala> // c116 -> a20

scala> //== Case Class : Compiler creates a Companion object for 'case class'

scala> //== (without us explicity providing a Companion object)

scala> //==              there by implementing factor pattern

scala> case class DbConnectorV2 {
     |   val url = "jdbc://..."
     |   val db = "mydb"
     |   val user = "myusername"
     |   val pwd = "mypwd"
     |   def connect()  = { println ("Connecting to DB...") }
     | }
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
defined class DbConnectorV2

scala> // ** Note : Here also we are not using new(). So this is an example

scala> //           of factory pattern

scala> val conn = DbConnectorV2()
conn: DbConnectorV2 = DbConnectorV2()

scala> conn.connect()
Connecting to DB...
The compiler also generates toString(), hashCode(), equals() & apply() among many methods for the case class

No comments:

Post a Comment