Scala case class and its companion object

Case class in Scala is special type of class definition that comes with a set of default features, like default construction, i.e. the new key word is not necessary to create an instance of the class.

case class BusinessName(name: String)

For example, if you define a case class BusinessName like above. Then you can use BusinessName(“Dyna-BI”) in your code directly. There are several other perks with case classes too, but one very recently addition is the companion object. The standards say every case class now comes with a default companion extractor object.

What that means is that, with above definition, you get an object called BusinessName too. And the object BusinessName would have the apply() and unapply() function defined automatically. Because of that, you can call its methods and BusinessName.unapply() right away. see following illustration.

scala> case class BusinessName(name: String)
defined class BusinessName

scala> BusinessName("Dyna-BI").name
res35: String = Dyna-BI

scala> BusinessName("Dyna-BI") == BusinessName.apply("Dyna-BI")
res36: Boolean = true

scala> BusinessName.unapply(BusinessName("Dyna-BI"))
res38: Option[String] = Some(Dyna-BI)