Scala — companion objects

In scala , companion object is an object with same name as class name.

example:
class employee {
}
object employee{
}

companion object and class will share its private members .

example
class employee {
def display = { println (“this is demo of access private”+securityname)}
}
object employee{
private val securityname = “secret”
}

apply method makes to create object with out newkey word , should be defined in object. apply is basically a constructor like thing , we can have more than one apply method to have multiple constructors concept.

example
class employee{
var name:option[String] =None
var age:option[Int]=None
override def toString= s “$name , $age”
}
object employee{
def apply(name:option[String]):employee = {
var s = new employee
s.name = name
s
}
def apply(name:option[String]):employee = {
var y = new employee
y.name=name
y.age=age
y
}
}
val employeeData = List(employee.apply(“sam”),employee(“ram”,22))

here we can call with apply method or with out apply method. if companion object doesnot have apply method and we create instance with new method , the compiler will throw error.

Developer