apply
This is the companion object method which is used to create instance of the concrete class. Using this, object can be created without new
keyword.
class Person(val name: String)
val person = Person("Nitin") // works
// Or
val person = new Person("Nitin") // works
Person("Nitin")
works because a companion object for Person
is generated implicitly with apply
method.
class Person(val name: String)
// companion object
object Person:
def apply(name: String): Map[String, String] =
Map("name" -> name)
val person = Person("Nitin")
// val res1: Map[String, String] = Map(name -> Nitin)
new Person("Nitin")
// val res2: Person = Person@1e592ef2
Calling Person
like function call, calls apply
method in companion object.
Using new
keyword doesn’t do that.
unapply
This is opposite of apply
method. This extracts the values from structure. Pattern matching uses this method extract the values from class objects.
class Person(val name: String)
object Person:
def unapply(person: Person): Option[String] =
Some(person.name)
val person = Person("Nitin")
person match
case Person(name) => println("Name : " + name)
So, pattern matching must be using Person.unapply
to destruct person instance.
val name = Person.unapply(person)