Case classes in Scala

A case class is an instantiable class that includes several automatically generated methods. It also includes an automatically generated companion object with its own automatically generated methods. The basic syntax of a case class in Scala is as follows:

case class <identifier> ([var] <identifier>: <type>[, ... ])[extends <identifier>(<input parameters>)] [{ fields and methods }]

A case class can be pattern matched, and comes with the following methods already implemented the method hashCode (location/scope is a class), apply (location/scope is an object), copy (location/scope is a class), equals (location/scope is a class), toString (location/scope is a class), and unapply (location/scope is an object).

Like a plain class, a case class automatically define, getter methods for the constructor arguments. To get a practical insight about the preceding features or a case class, let's see the following code segment:

package com.chapter3.OOP 
object CaseClass {
def main(args: Array[String]) {
case class Character(name: String, isHacker: Boolean) // defining a
class if a person is a computer hacker
//Nail is a hacker
val nail = Character("Nail", true)
//Now let's return a copy of the instance with any requested changes
val joyce = nail.copy(name = "Joyce")
// Let's check if both Nail and Joyce are Hackers
println(nail == joyce)
// Let's check if both Nail and Joyce equal
println(nail.equals(joyce))
// Let's check if both Nail and Nail equal
println(nail.equals(nail))
// Let's the hasing code for nail
println(nail.hashCode())
// Let's the hasing code for nail
println(nail)
joyce match {
case Character(x, true) => s"$x is a hacker"
case Character(x, false) => s"$x is not a hacker"
}
}
}

The preceding code produces the following output:

false 
false
true
-112671915
Character(Nail,true)
Joyce is a hacker

For the REPL and the output of the regular expression matching, if you execute the preceding code (except the Object and main method), you should be able to see the more interactive output as follows:

Figure 2: Scala REPL for case class
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.69.240