Case classes

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 ...

Get Learning Scala Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.