Table of contents
1.
Introduction
2.
Case Class in Scala
2.1.
Characteristics of Case Class in Scala
2.2.
Benefits of Case Class in Scala
3.
Case Object in Scala
3.1.
Characteristics of Case Object in Scala
3.2.
Benefits of Case Object in Scala 
4.
Case Class Examples
4.1.
Defining of Case Class 
4.2.
Comparing Two Case Classes
4.3.
Shallow Copying a Scala Case Class
4.4.
toString Method in Case Class
4.5.
Duplicate Same Object with Changing Attributes
5.
Difference between Class and Case Class
6.
Frequently Asked Questions
6.1.
What is Scala Programming language?
6.2.
What do you mean by Case Class in Scala?
6.3.
What do you mean by a Shallow copy?
6.4.
What do you mean by a Case Object in Scala?
6.5.
How can we define a minimal case class in Scala?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Scala Case Class and Case Object

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Scala case classes are regular classes that are automatically immutable and can be deconstructed using pattern matching.

It employs the 'equal' method to compare instances structurally and does not require the 'new' keyword for object instantiation.

All parameters in the case class are publicly accessible and immutable by default. 

Case Class and Case Object in Scala

Recommended Topic, 8085 Microprocessor Pin Diagram

Case Class in Scala

Case classes in Scala are regular classes with some extra toppings that are immutable by default. Let’s discuss why they are in high demand. 

A case class with no arguments is declared as a case object rather than a case class. By default, the case object can be serialized. Case class in Scala is constructive in pattern matching.

After that, by default, case classes have public and immutable parameters. In addition, These support pattern matching, making it easier to write logical code.

The Case class in Scala has a default apply() method, which manages the construction of objects.

Before moving toward the examples, let’s check out some characteristics of the case class in Scala.

Characteristics of Case Class in Scala

  1. Scala produces methods like equals(), hashcode(), and toString() automatically as part of the case class.
  2. An instance can be created without using the ‘new‘ keyword.
  3. Scala produces methods like equals(), hashcode(), and toString() automatically as part of the case class.
     

Benefits of Case Class in Scala

  1. Easy to use in Pattern Matching.
  2. It is immutable.
  3. Case class constructor parameters are val fields by default.
  4. A case class generates a copy() method that is helpful when you want to clone an object or want to update one or more fields during the cloning process.

Case Object in Scala

A case object in Scala is just like an object which has more attributes than a regular object. It is a blend of both case classes and objects.

Characteristics of Case Object in Scala

  1. It has a by default hashCode implementation.
  2. It is serializable
     

Benefits of Case Object in Scala 

  1. Case objects are used when the enumeration is to be done.
  2. Other benefits of case objects is when we want to model the concept of the messages.

Recommended Topic, Cognizant Eligibility Criteria

Case Class Examples

This section will cover some examples of case class in Scala.

Syntax:

case class className(parameters)  

Defining of Case Class 

We have to define a minimal case class; for this, we need the keywords as a case class, an identifier, as well as a parameter list.

// Class case and class object example
case class Color(name: String)
object Main
{
	def main(args: Array[String]) 
    { 
		val x = Color("Orange")
		val y = Color("Red");
		println(x.name);
		println(y.name);
	}
}


Output:

Defining of case class

Explanation:

Have you noticed that the keyword new was not used to instantiate the Color case class? The reason behind this is that case classes have an apply() method by default which takes care of object construction.

Comparing Two Case Classes

Let’s take a look at how to compare two case classes. Here instances of case classes are compared by structure.

// Comparison of two case class 
case class User(Name: String, age: Int)
object Main
{
	def main(args: Array[String]) 
    { 
    	val c1 = User("Sagar", 19)
     	val c2 = User("Sagar", 19)
     	val c4 = User("Neha", 19)
	    val c3 = c1 == c2 
        val c5 = c1 == c4
        println(c3);
        println(c5);
      }
}


Output:

Output of comparing two Case Classes

Explanation:

As we see in the above example, variables c1 and c2 are equal, but variables c1 and c4 are not; therefore, for variable c3 true is printed, and for c5 false has been printed.

Shallow Copying a Scala Case Class

Since a Scala case class is immutable, we need a copy to make changes without changing the original. So, we now see how to create a shallow copy of it.

Shallow Copy

Example:

// Demonstrating the copy() method
object CaseClass extends App {
  case class Color(name: String)
    val c1 = Color("Yellow")
    val c2 = c1.copy()
    println(c2.name)
    println(c1 == c2)
}


Output:

Output

Explanation:

As we see in the above example, you can create a copy(shallow) of an instance of a case class simply by using the copy() method.

toString Method in Case Class

Let’s see an example of the toString method in the case class in Scala.

// Use of toString() method in case class 
case class Bags(color: String, count: Int)

object Main
{
    def main(args: Array[String])
    {
    val x = Bags("Black", 159)
    val y = x.count.toString
    println("length of converted count is : " + y.length);
    }
}


Output:

toString() method

Explanation:

In the above example, the toString() method returns the int value in string format. So the count of bags was 159, and then after applying the toString method, it converted to 3.

Duplicate Same Object with Changing Attributes

Let’s see how to duplicate the same case object with changing attributes.

// Example of a duplicate of the same object with changing attributes.
case class User(name: String, age: Int)
object Main
{
    def main(args: Array[String])
    {
    	val c1 = User("Neha", 27)
          
        // Display parameter
        println("Name is: " + c1.name);
        println("Age is: " + c1.age);
        val c2 = c1.copy(age = 29)
          
        // Display copied and changed attributes
        println("Copy Name is: " + c2.name);
        println("Change Age is: " + c2.age);
      }
}


Output:

Output

Explanation:

Here you need to pass the new value in the copy method.

You can also read about mock interview.

Difference between Class and Case Class

The following table describes the difference between Class and Case Class:

Feature

Class

Case Class

Syntax The normal class is defined by defining methods and fields. The case class is defined using parameters in a single statement.
Pattern Matching Regular class did not support pattern matching. Case class supports pattern matching.
Methods Regular class does not have predefined methods. Case class has predefined methods like hashcode and equal.
Inheritance Regular class can be inherited by another class. Whereas case class cannot be inherited or extended.
Comparison of objects The comparison is made as reference(memory). The objects of case class are copied(using shallow copy) and the comparison is made by comparing the structure.

 

Check out this problem - Duplicate Subtree In Binary Tree

Frequently Asked Questions

What is Scala Programming language?

Scala is an object-oriented, high-level programming language that supports the functional programming approach.

What do you mean by Case Class in Scala?

Case classes in Scala are regular classes with some extra toppings that are immutable by default.

What do you mean by a Shallow copy?

A shallow copy is one where changes to the copy reflect the original.

What do you mean by a Case Object in Scala?

A case object is just like an object but has more attributes than a regular object. A case object has more features than a regular object.

How can we define a minimal case class in Scala?

To define a minimal Scala Case Class, we need the keywords ‘case class’, an identifier, and a parameter list. We can keep the parameter list empty.

Conclusion

Thanks, Ninjas, for making it to the end of the blog. Hope you enjoyed it and have gained some knowledge about case class in Scala, case objects in Scala, Comparison of two case classes, Shallow copying of a scale case class, the toString method in case class, and at last, how to create a duplicate of the same object with changing the attributes with the help of the examples.

You can refer to more articles similar to this

  1. Scala Language
  2. Scala Interview Questions
  3. For loop in Scala
  4. Closure in Scala
  5. Higher order functions in Scala
     

Check out The Interview guide for Product Based Companies and some of the Popular Interview Problems from Top companies like AmazonAdobeGoogleUberMicrosoft, etc., on Coding Ninjas Studio.

Also, check out some of the Guided Paths on topics such as Data Structures and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Happy learning!

Live masterclass