Tuesday, September 13, 2016

Companion Class & Companion Object : Example...

A Companion object is an object that carries the Same name of the class it is supporting. In this example we have used Companion object to implement a Factory Object to instantiate the class Subject without the need to use new keyword #107
scala> :paste
// Entering paste mode (ctrl-D to finish)

class Subjects{
   private var subjectList:List[String] = Nil
   def addSubject(subject:String):Unit = {
     subjectList = subject :: subjectList
   }
   def getSubjects():List[String] = subjectList
}

object Subjects{
   def apply():Subjects = new Subjects()
}

// Exiting paste mode, now interpreting.

defined class Subjects
defined module Subjects

scala> // No need to use 'new' here...

scala> val subjects = Subjects()
subjects: Subjects = Subjects@385e9564

scala> subjects.addSubject("math")

scala> subjects.addSubject("Science")

scala> subjects.getSubjects()
res2: List[String] = List(Science, math)