What are case classes, why do we have them, and how do we use them? These are a few questions you may want an answer to. So, in simpler words, a case class can omit the amount of code we may have to write to achieve this:
class Country(val name: String, val capital: String) { override def toString: String = s"Country($name,$capital)" override def equals(obj: scala.Any): Boolean = ??? override def hashCode(): Int = ??? }
Instead of declaring Country
as we do in the preceding code, we would prefer to do the following:
case class Country(name: String, capital: String)
And our case class Country
definition takes care of the rest. We have accessor methods for our name
and capital
members. We have our toString
and equals
methods defined by the Scala compiler, or let's say, auto-generated for us:
case class Country(name: String, capital: String) object CountryUtil extends App { val country = Country("France", "Paris") println(s"Our country is: $country") ...