Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-21 03:35:22 Viewed : 634
In Scala, case classes are a special type of class that are primarily used to store and transport data. They come with several built-in features such as pattern matching, automatic generation of companion objects, and implementations of equals
, hashCode
, and toString
methods. Pattern matching is a powerful mechanism in Scala that allows for concise and readable handling of different cases. Her is an overview of case classes and pattern matching in Scala:
Case Classes:
case class
keyword.new
keyword.scalacase class Person(name: String, age: Int)
Pattern Matching:
match
expressions to apply different logic based on the pattern matched.scalaval person = Person("Alice", 30) person match { case Person(name, age) => println(s"Name: $name, Age: $age") case _ => println("Not a person") }
In this way, case classes and pattern matching work together to facilitate the creation and manipulation of data structures, providing concise and powerful mechanisms for data handling and control flow in Scala.
Below are examples of case classes and pattern matching in Scala, along with the corresponding outputs:
Example of a Case Class:
scala// Defining a case class case class Person(name: String, age: Int) // Creating an instance of the case class val person = Person("Alice", 30) // Accessing fields of the case class println(person.name) // Output: "Alice" println(person.age) // Output: 30
Example of Pattern Matching:
scala// Defining a case class case class Person(name: String, age: Int) // Using pattern matching with the case class val person1 = Person("Alice", 30) val person2 = Person("Bob", 25) def matchPerson(p: Person): String = p match { case Person("Alice", 30) => "Hello Alice!" case Person(name, age) => s"Name: $name, Age: $age" } // Matching the first person val result1 = matchPerson(person1) println(result1) // Output: "Hello Alice!" // Matching the second person val result2 = matchPerson(person2)println(result2) // Output: "Name: Bob, Age: 25" } // Matching the first person val result1 = matchPerson(person1) println(result1) // Output: "Hello Alice!" // Matching the second person val result2 = matchPerson(person2) println(result2) // Output: "Name: Bob, Age: 25"
In this example, we define a case class Person
with fields name
and age
. We then create instances of the Person
case class and access their fields. Next, we use pattern matching with the match
expression to check different cases of the Person
instances. The output demonstrates the matching results based on the defined cases.