Showing posts with label C0168| toString(). Show all posts
Showing posts with label C0168| toString(). Show all posts

toString() : 'Simple class' vs 'Case class' Comparison

For a case class, Scala compiler automatically generates many methods including  toString() method
scala> // Simple class example

scala> class SimpleClass {
     | }
defined class SimpleClass

scala> val obj1 = new SimpleClass
obj1: SimpleClass = $iwC$$iwC$SimpleClass@26622cf0

scala> obj1.toString()
res8: String = $iwC$$iwC$SimpleClass@26622cf0

scala>

scala> // Case class example

scala> case class MyCaseClass {
     | }
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
defined class MyCaseClass

scala> val obj2 = MyCaseClass()
obj2: MyCaseClass = MyCaseClass()

scala> obj2.toString()
res9: String = MyCaseClass()

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