Case class
A case class provides the same facilities as a normal class, but the compiler generates toString, hashCode, and equals methods (which you can override).
Case classes can be instantiated without the use of the new statement.
By default, all the parameters in the case class’s constructor become properties on the case class.
Creating a Case class
To create a case class, we can add case keyword before the class declaration as follows :
case class Person(firstName:String,lastName:String)
We can instantiate a case class without the keyword “new”. You may still use the new keyword, but its not necessary.
e.g.,
val person = Person("John","Doe");
Accessing parameters in case class
Scala prefixes all the parameters with val, and that will make them public value.
We can access the parameters as shown in below example :
val person = Person("John", "Doe"); println("FirstName : " + person.firstName); println("LastName : " + person.lastName);
Output:
FirstName : John
LastName : Doe
toString() in case class
The compiler implements the toString method that returns the class name and its parameters.
For example,
val person = Person("John", "Doe"); println(person.toString());
Output:
Person(John,Doe)
hashCode and equals in case class
Both equals and hashCode are implemented for you based on the given parameters.
The equals method does a deep comparison:
val person = Person("John", "Doe"); println(person == Person("John", "Doe")) println(person == Person("Johny", "Doe"))
Output:
true
false
copy method in case class
Every case class has a method named copy that allows you to easily create a modified copy of the class’s instance.
For example, below code creates a copy of person with firstName as “Dave”, but same lastname:
val person = Person("John", "Doe"); val anotherPerson = person.copy(firstName = "Dave") println(anotherPerson)
Output:
Person(Dave,Doe)
© 2016, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post