O'Reilly logo

Learning Scala Programming by Vikash Sharma

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required