Case classes in Scala

Reading Time: 3 minutes

Overview

In this blog post we will look at what are case classes in Scala and how this feature supports functional programming. Case classes have all the properties of normal classes plus properties of its own. We will discuss more in this blog. If you are familiar with basic Scala syntax you’ll be able to follow along, you can refer to official Scala documentation to get hold of basic syntax.

Blog Poster

Case classes

Whenever compiler finds keyword “case” before “class” it generates a code for you, with some benefits. Let’s see some of the benefits in detail.

  1. Case classes constructor parameters are public “val” fields, Hence methods that access are generated for each parameter
  2. “apply” method is created in the companion object so we need not to use “new” keyword and instantiate the class
  3. An “unapply” method is also generated that enables us to use it in match expressions, we will look at it in brief further in this blog post.
  4. A “copy” method is generated that is widely used in Scala Functional Programming

The above 4 features are the one’s that we’ll discuss in this blog, the other few features are “equals”, “hashcode” and “toString” method that is widely used for debugging. To know more about these specific features refer this page.

The “apply” method!

When we say we do not need to use new keyword while instantiating the case class, let’s see what exactly it’ll look like.

scala> case class Animal(name: String, type: String)
defined class Animal

// "new" not required
scala> val duck = Animal("Donald Duck", "Can Speak")
duck: Animal = Animal(Donald Duck,Can Speak)

As discussed the above snippet is perfectly fine as we know apply method is already generated in the companion object of the case class.

Methods that cause mutations are not allowed!

Let’s look at the following code and try to understand what is being said!

scala> duck.name
res0: String = Donald Duck

The above code is working properly in context to the previous block. Let’s see what happens when we try to mutate the value of name.

// cannot mutate the `name` field
scala> duck.name = "Daisy Duck"
<console>:10: error: reassignment to val
       duck.name = "Daisy Duck"
                  ^

See, the code will not run as the constructor parameter of the case class is a public val type-of field. As it is advised in functional programming that never to mutate the data, these fields are set as public val.

The “unapply” method!

Let’s try to understand this method using traits.

trait Animal {
    def name: String
}

The following classes are extending the above trait.

case class duck(name: String, age: Int) extends Animal
case class mouse(name: String, haveTail: String) extends Animal

As they are the case classes we can use them as expressions in pattern matching with match keyword.

def getPrintableString(p: Animal): String = p match {
    case duck(name, age) =>
        s"$name is an animal of age $age."
    case mouse(name, haveTail) =>
        s"$name animal have $haveTail."
}

Let’s run this!

val duckVal = duck("Donald Duck", 8)
val mouseVal = mouse("Frog", "no tail")

// Now if I try to pass it in getPrintableString() method

scala> getPrintableString(duckVal)
res0: String = Donald Duck is an animal of age $age.

scala> getPrintableString(mouseVal)
res1: String = Frog animal have no tail.

The “copy” method!

Case classes are having this method automatically generated which comes very handy in functional programming. As the name suggest the method just copy with or without arguments when provided. Last line sounded tricky? let’s try to implement it!

scala> case class IplTeam(name: String, lastWin: Int)
defined class IplTeam

scala> val year2019 = IplTeam("MI", 2019)
cubs1908: IplTeam = IplTeam(MI,1908)

scala> val year2020 = year2019.copy(lastWin = 2020)
cubs2016: IplTeam = IplTeam(MI,2020)

So what happened is, we just provided the arguments we needed to modify during in the method and it updated it easily ! To know more about the remaining methods check out this page.

Conclusion

In this blog we talked about some features of case classes that is: “apply”, “unapply” and “copy”. I hope it’s help.

Thanks for reading this blog. Check out our website knoldus.com for engineering solutions and you can find more awesome blogs at https://blog.knoldus.com.

Scala Future

1 thought on “Case classes in Scala4 min read

Comments are closed.