This article is part of the Scala knowledge bits Series.
Periodically, I will publish new exercises so you can slowly build up knowledge about Scala.
It is designed to be done in a very short amount of time and learn a little bit each day, just to create a routine.
This episode will teach you about Scala Case Class.
Hope you are going to enjoy it! It is designed for anyone to learn Scala from scratch and slowly learn, one Bit at a time.
After this Bit, I would love to hear your feedback in the comments down below.
Feel free to join the Discord server as well if you would like some help and support from the rest of our community.
What are we learning today?
Today we are going to learn about Scala Case Class !
We learned about
in a previous SKB, today we are going to learn about
. They serve the same purpose which is to provide a blueprint to create
s. But case class provides a lot of build-in advantages.
As a start, notice how the case class is being instantiated, and how the fields are being accessed.
Time to try on the exercise on your own and scroll down for more information when you are done or if you are stuck.
Here is an exercise to complete today.
If I did my job well, you should be able to guess by yourself the solution based on what you previously learned and based on the clues.
But if you get stuck, scroll down to get more information.
The goal of the exercise is to replace the
by a piece of code so that the exercise compiles and that’s how you win! Good luck!
You can fill the exercise right in here:
Or, if it does not load, go on to Scastie (2cLIBX4MTeK7xf7fXBPI4A).
More information about Scala Case Class
In this exercise you will learn (or have learned, if you have already solved the puzzle) about Scala Case Class.
Did you notice that we do not need
to create the instance of the
And did you notice that we do not need a function to access any of the fields?
provide build-in things, let’s go over them:
- Constructor: To instantiate an object from a case class, no need for the
newkeyword. Note that
classwill not need
neweither in Scala 3. To understand how this is done, remember the words
Companion Object, we are going to come back to it later.
- Field accessors: in
case class, the field are
public( we are going to talk about
visibilitylater ) by default. So you can access their values without the need to a method that will return it for you.
- And more; remember the terms
Serializationfor later SKBs.
Feel free to go back to the exercise, modify the code to try out new things and get a better intuition for Scala Case Class.
I hope you have learned something new or had fun during this Scala Knowledge Bit.
Please ask questions or post feedback in the comments below.
Feel free to try on the next Scala Knowledege Bit.
If you are curious about the previous Scala knowledge Bits, go check it out! 🙂