Enhance your Knowledge | Flat 25% Discount on all Courses | Use Coupon Code - ENHANCE25 During Checkout |Enroll Now
Case classes are regular classes that are immutable by default. Immutability helps us in writing classes without worrying about or keeping track of where and when things are mutated. This, in turn, helps in writing code which does not act weird.
Case classes can be pattern matched. Pattern matching simplifies the branching logic and helps in writing more readable code.
For case classes, the compiler automatically generates the hashcode and equals method, hence less code.
It is recommended to use case classes as they help in writing more expressive and maintainable code
Let's understand case classes and pattern matching with a demo. We've provided sample code on CloudxLab GitHub repository. Clone the repository if you haven't else update it
Now go to the case_classes directory and open case_class.scala file. We have defined two case classes Email and SMS. Note that we define a case class using "case" keyword. Both SMS and Email case classes extend the notification class which is an abstract class.
We've created two instances of the SMS class with same parameters. We can compare them with == operator. Run the file and as you can see that the two instances are equal.
Let's understand pattern matching with an example. Open pattern_matching.scala. Here we've defined a function showNotification which takes Notification class instance as an argument and its return type is a string. Here, we're matching notification instance with the case class. As we are passing the instance of SMS class to this function, it will match the case SMS and return the corresponding string. Let's run the file and as you can see "You got an SMS from number 12345 Message: Hello" is printed on the screen.
The URL for repository is https://github.com/cloudxlab/bigdata And the case class example code is available here: https://github.com/cloudxlab/bigdata/blob/master/scala/case_classes/case_class.scala
Taking you to the next exercise in seconds...