apply
, unapply
and update
Create instance without new
In scala, we can create an instance of a class without using keyword new
. When we do this, scala does something behind the scenes. It creates a companion object of the class and creates an apply
method which returns the instance of the class.
class A(var value: Int)
val a = A(1)
// companion object
object A {
def apply(value: Int): A = new A(value)
}
Calling the instance
class A(var value: Int):
def apply: Int = value
val a = A(1)
println(a()) // prints 1
Defining apply
in the class itself makes the instance callable like a method.
update
class A(var value: Int):
def update(newVal: Int): Unit = value = newVal
val a = A(1)
a() = 2
a.value // 2
It is a syntactic sugar for updating a value in an instance of a class. Scala compiler converts a() = 2
to a.update(2)
.