Scala Case Class – How to Create Scala Object

Free Scala course with real-time projects Start Now!!

In this Scala tutorial, we will see how to define a Scala case class. Moreover, we will also take a look at how to compare case classes and create shallow copies. Along with this, we will also learn how to create a Scala object.

So, let’s explore Scala Case Class and Scala Object.

Read Scala Syntax: An Introductory Scala Tutorial

What is Scala Case Class?

A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.
Let’s Revise Scala Syntax with example.

Defining 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.
So, let’s define a class ‘Song’.

scala> case class Song(title:String,artist:String,track:Int)

Creating a Scala Object

And now, it’s time to create a Scala Object for this Scala class.

scala> val stay=Song("Stay","Inna",4)
stay: Song = Song(Stay,Inna,4)

To create a Scala Object of a case class, we don’t use the keyword ‘new’. This is because its default apply() method handles the creation of objects.
Let’s try accessing the title of this object:

scala> stay.title
res1: String = Stay
And now, let’s try modifying it.
scala> stay.title="Me Gusta"
<console>:12: error: reassignment to val
      stay.title="Me Gusta"

Explore Scala Closures with Examples | See What is Behind the Magic
So, this tells us that Scala case classes hold all vals, and this makes them immutable. We cannot reassign them. And while it is discouraged to do so, we can use vars in a case class.

Comparing two Case Classes

Now, let’s take a look at how to compare two Scala case classes. 

scala> val crybaby=Song("Cry Baby","Melanie Martinez",7)
crybaby: Song = Song(Cry Baby,Melanie Martinez,7)
scala> val cry_baby=Song("Cry Baby","Melanie Martinez",7)
cry_baby: Song = Song(Cry Baby,Melanie Martinez,7)
They hold the same contents, but are they the same? Let’s ask Scala.
scala> crybaby==cry_baby
res2: Boolean = true
Yes. Yes, they are.

Shallow-Copying a Scala Case Class

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Since a Scala case class is immutable, we might sometimes need a copy to make changes in without changing the original. So, we now see how to create a shallow copy of it. But before that, let’s see a little about shallow and deep copies.

A deep copy is a copy to another object where any changes we make to it don’t reflect in the original object.

Scala Case class

Scala Case class- Deep copy

A shallow copy, however, is one where changes to the copy do reflect in the original.

Scala Case class

Scala Case class- Shallow copy

So, Scala uses the method copy() to carry out a shallow copy.

scala> val chandelier1=chandelier.copy()
chandelier1: Song = Song(Chandelier,Sia Furler,3)

It is also possible to change the constructor arguments.

scala> val chandelier2=chandelier.copy(title=chandelier.artist,artist="Sia")
chandelier2: Song = Song(Sia Furler,Sia,3)

So, this was all about Scala Case Class and Scala Object. Hope you like our explanation.

Conclusion: Scala Case Class and Scala object

So, this is how we define a case class and process it. Hence, we saw Scala Case Class. Moreover, we discussed Creating a Scala object. Also, we compared two Scala Case Classes. Finally, we looked at shallow copying a Scala Case Class. Furthermore, feel free to leave your doubts and suggestions in the comment section.
For reference

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

14 Responses

  1. hari says:

    A deep copy is a copy to another object where any changes we make to it don’t reflect in the original object.
    Scala Case class
    Scala Case Class- Deep Copy
    A shallow copy, however, is one where changes to the copy don’t reflect in the original.
    Scala Case class
    I think there deep copy definition is wrong

    • hari says:

      sorry other way around

    • Data Flair says:

      We Appreciate your Observation on “Scala Case Class”. We have updated our content.
      “Since a deep copy copies to another object, altering the object will not alter the original object. This isn’t the same with a shallow copy, where if you make changes to an object, it will affect the original object.”
      Keep visiting and Keep Learning from Data-Flair

  2. Sonali says:

    Deep copy and shallow copy explanations are quite confusing .

    • Data Flair says:

      Thanks Sonali to give us chance to solve your query on “Scala Case Class”.
      A shallow copy duplicates very little. It copies the structure, not the values. Two objects, where one is the shallow copy to another, share values. Hence, changing one will change another.
      However, a deep copy duplicates everything. Since it duplicates all values too, any changes to it will not affect the original object.”
      Hope we solve your query, you should also try the Scala Quiz to explore and learn Scala Programming

      • Hadi says:

        I think you can say that a shallow copy is look like a new pointer to the original object. In other words, your sentence “a shallow copy dupicates very little” is not so clear !!

        • DataFlair Team says:

          Hey Hadi,
          Thanks for interacting with DataFlair, let’s clear this up for once.

          Scala shallow copy operation creates a new compound object and inserts in it the same objects held by the original.

          Scala deep copy operation creates a new compound object, then inserts in it copies of the objects held by the original.

          Changes to the new compound object do reflect in the original for shallow copy operations. Hope, it helps you!

  3. Steve says:

    #5 isn’t accurate. Use `eq` instead of `==` for equality in Scala. Check out

    • DataFlair Team says:

      Thanks, Steve, to comment and connect with DataFlair with this Scala case classes tutorial.

      Indeed, the ‘eq’ method is great with reference equality. It, however, can be risqué to throw it around unless you know exactly how it works. To keep things simple, we use the == operator instead in our example. It also works well with null references.
      Hope, it will help you!

  4. ramesh says:

    my kind request font and white color background is not good to see the texts…..

    • DataFlair Team says:

      Hi Ramesh,
      Thanks for the suggestion. We continuously strive to improve the experience for our users. Soon, we will provide you with The Best Learning Platform.

  5. mahendra says:

    Using copy method we can create another instance of scala case class object, In this case if we change the copied instance, then changes will get reflected in original instance also, then how original scala case class becomes Immutable one..?

  6. Ravi says:

    1. Why do we need Case Class copy with constructor?

    2. How it is different than creating a separate case class with same number of constructor arguments with different values?

    3. When you create a Case Class object from original object with different values, original object contains original value and new object contains the newer values specified while creating case class object; however as per description above doing a shallow copy with “copy” method should create two different case class objects with same values. Could you please explain this behavior?

    4. I tried modifying the value of new Case Class object which was copied from original and it threw error saying “reassignment to val”. Could you please explain this behavior?

  7. vishal says:

    according to your definition Scala must follow the deep copy not shallow copy. But you mentioned scala follow shallow copy. Is it not cofusing.?

Leave a Reply

Your email address will not be published. Required fields are marked *