Open In App

Scala – Generating Boilerplate Code With Case Class

Improve
Improve
Like Article
Like
Save
Share
Report

Scala Case classes come shipped in with many handy methods. The Scala compiler generates boilerplate code when a case class is defined. This does away with writing redundant code which otherwise developers need to write for normal classes.

Some of the methods that are generated as boilerplate code are as follows:

  •  setter
  •  getter
  •  apply()
  •  unapply()
  •  toString
  •  equals
  •  hashCode
  • copy()

A getter and setter method for defining and retrieving class members. Constructor parameters in case classes are automatically promoted to class members. So, to set class members all we need to do is pass the values as constructor parameters. By default, they are promoted to val. We can, however, explicitly declare them as var.

Example 1:

Scala




// A case class named Language.
case class Language(title: String, rating: Double)
object Main {
    def main(args: Array[String]) {
        val CvsJava: Language = Language("C vs Java", 7.4)
          // Constructor parameters of the case class are class members.
          println(s"Language name: ${CvsJava.title} rating: ${CvsJava.rating}")
    }
}


Output:

 

The Scala compiler generates the toString method. In the example below we could see that for objects of case classes, the println statement prints a readable string representation of the object. But for objects of normal classes, its hash is printed.

Example 2: 

Scala




case class Movie(title: String, rating: Double)
class AdFilm(title: String, lengthInSeconds: Int)
  
object Main {
    def main(args: Array[String]) {
        val fordVsFerrari: Movie = Movie("Ford vs Ferrari", 7.4)
          // Prints the string representation of the object.
          println(fordVsFerrari)
          val nikeAdFilm: AdFilm = new AdFilm("Nike Jordan", 185)
          // Prints the hash of the object.
          println(nikeAdFilm)
    }
}


Output:

 

 

Equals and hashCode methods are automatically generated for case classes. This allows us to compare objects of case classes.

Example 3:

Scala




case class Subject(title: String, rating: Double)
object Main {
    def main(args: Array[String]) {
        val Stream1 = Subject("Stream1", 8.2)
          val Stream2 = Subject("Stream1", 8.2)
          var isEqual =Stream1  == Stream1
          println(isEqual)
          val CvsCsharp = Subject("CvsCsharp", 7.4)
          isEqual = Stream1 == CvsCsharp
          println(isEqual)
    }
}


Output:

 

The Scala compiler generates a companion object for the case class with the apply() factory method. This apply() method takes in parameters the same as the constructor parameters of the case class. The syntactic sugar of the apply() method allows us to create instances of a case class without using the new keyword.

Example 4:

Scala




case class NewLanguage(title: String, rating: Double)
object Main {
    def main(args: Array[String]) {
          // Object creation without the new keyword.
        val Scala = NewLanguage("Scala", 8.2)
          println(Scala)
    }
}


Output:

 

Out-of-the-box implementation of the unapply() method. The unapply() method extracts member values of an object. This allows us to use instances of case classes in pattern matching.

Example 5:

Scala




case class NewLanguage(title: String, rating: Double)
object Main {
    def main(args: Array[String]) {
        val stream = NewLanguage("Scala", 8.2)
          stream match {
             case NewLanguage("CSharp", _) =>
                    println("Developed: Microsoft, Anders Hejlsberg")
             case NewLanguage("Scala", _) =>
                    println("Developed: EPFL, Martin Odersky")
              case _ =>
                    println("No match found")
          }
    }
}


Output:

 

The Scala compiler automatically adds a copy() method to the case class. With the copy() method we can create a new object of the case class with the same attributes or with some modified attributes.

Example 6:

Scala




case class Movie(title: String, rating: Double)
object Main {
    def main(args: Array[String]) {
        val fightClub = Movie("Fight Club", 8.2)
          val fightClub2 = fightClub.copy(rating = 8.4)
          // fightClub2 is a new object with different value for rating field.
          val isEqual = fightClub == fightClub2
          println(isEqual)
    }
}


Output:

 

To sum it up case classes are a powerful feature of Scala that eases development to a great extent. This is because the Scala compiler generates boilerplate code at compile time which is not possible with normal classes. 



Last Updated : 08 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads