Scala Tutorial - Learn How To Define And Use Case Class

By Nadim Bahadoor | Last updated: March 16, 2018 at 13:15 pm

Overview

In this tutorial, we will learn how to define case class and use it to create instances of objects.

 

What is a case class?

A case class is similar to any other classes except that it also creates the Companion Object. In addition, a case class will automatically create the apply(),  toString(), hashCode and equals() methods for you.

Steps

1. How to define a case class to represent a Donut object

Defining a case class is similar to defining a simple class as we've discussed in the Learn How To Create Class And Objects Tutorial. However, you also make use of the case keyword as part of the class definition.


println("Step 1: How to define a case class to represent a Donut object")
case class Donut(name: String, price: Double, productCode: Option[Long] = None)

2. How to create instances or objects for the Donut case class

Use the following syntax to create instances or objects of the Donut case class.


println("\nStep 2: How to create instances or objects for the Donut case class")
val vanillaDonut: Donut = Donut("Vanilla Donut", 1.50)
val glazedDonut: Donut = Donut("Glazed Donut", 2.0)
println(s"Vanilla Donut = $vanillaDonut")
println(s"Glazed Donut = $glazedDonut")

You should see the following output when you run your Scala application in IntelliJ:


Step 2: How to create instances or objects for the Donut case class
Vanilla Donut = Donut(Vanilla Donut,1.5,None)
Glazed Donut = Donut(Glazed Donut,2.0,None)

NOTE:

  • You did not have to use the new keyword when creating instances of the Donut case class.
  • The case class will automatically create the Companion Object.

3. How to access fields of the Donut object

When using a case class, you do not have to write any boiler plate accessor code to be able to access the fields on objects created from a case class.


println("\nStep 3: How to access fields of the Donut object")
println(s"Vanilla Donut name field = ${vanillaDonut.name}")
println(s"Vanilla Donut price field = ${vanillaDonut.price}")
println(s"Vanilla Donut productCode field = ${vanillaDonut.productCode}")

You should see the following output when you run your Scala application in IntelliJ:


Step 3: How to access fields of the Donut object
Vanilla Donut name field = Vanilla Donut
Vanilla Donut price field = 1.5
Vanilla Donut productCode field = None

4. How to modify or update fields of the Donut object

As you have learned from the Scala Programming Features tutorial, Scala favours the use of immutability. As a results, fields defined on case class are immutable by default and as such you cannot modify them.


println("\nStep 4: How to modify or update fields of the Donut object")
// vanillaDonut.name = "vanilla donut" // compiler error. fields are immutable by default.

5. How to define the hashCode and equals method for Donut object

As mentioned earlier, when you use a case class, the Scala compiler automatically creates the hashCode and equals() methods for you.

 

As an example, let's create a Map to represent the type and quantity of donuts being bought by our customers. If you do not implement the hashCode method, adding and retrieving elements from the Map will give you unpredictable behaviour.

 

However, since we are using the case class to represent the Donut objects, the hashCode method is implemented for us!


println("\nStep 5: How to define the hashCode and equals method for Donut object")
val shoppingCart: Map[Donut, Int] = Map(vanillaDonut -> 4, glazedDonut -> 3)
println(s"All items in shopping cart = ${shoppingCart}")
println(s"Quantity of vanilla donuts in shopping cart = ${shoppingCart(vanillaDonut)}")
println(s"Quantity of glazed donuts in shopping cart = ${shoppingCart(glazedDonut)}")

You should see the following output when you run your Scala application in IntelliJ:


Step 5: How to define the hashCode and equals method for Donut object
All items in shopping cart = Map(Donut(Vanilla Donut,1.5,None) -> 4, Donut(Glazed Donut,2.0,None) -> 3)
Quantity of vanilla donuts in shopping cart = 4
Quantity of glazed donuts in shopping cart = 3

This concludes our tutorial on Learn How To Define And Use Case Class and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to define a case class to represent an object
  • How to create instances or objects for a given case class
  • How to access fields on objects which are based on case class
  • How to modify or update fields on objects which are based on case class
  • How to define the hashCode and equals method for objects which are based on case class

Tip


println("\nTIP: How to create a new object of Donut by using the copy() method of the case class")
val chocolateVanillaDonut: Donut = vanillaDonut.copy(name = "Chocolate And Vanilla Donut", price = 5.0)
println(s"Chocolate And Vanilla Donut = $chocolateVanillaDonut")

You should see the following output when you run your Scala application in IntelliJ:


TIP: How to create a new object of Donut by using the copy() method of the case class
Chocolate And Vanilla Donut = Donut(Chocolate And Vanilla Donut,5.0,None)

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to use Type Aliasing in Scala.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: