Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-09-27 17:05:43 Viewed : 87
In Scala, a case class is a special type of class that is primarily used for modeling immutable data. Case classes come with a number of built-in features that make them convenient for representing data structures. Some of these features include automatic generation of equality, hash code, and toString methods, as well as pattern matching support. Here are some examples of case classes in Scala:
Simple Case Class:
scalacase class Person(name: String, age: Int)
This defines a Person
case class with two fields: name
of type String
and age
of type Int
. Case classes automatically generate an equals
, hashCode
, and toString
method for you.
scalaval person1 = Person("Alice", 30) val person2 = Person("Bob", 25) println(person1) // Output: Person(Alice,30) println(person1 == person2) // Output: false
Pattern Matching with Case Class:
Case classes are often used with pattern matching, which is a powerful feature in Scala. Here is an example of pattern matching with a case class:
scaladef greet(person: Person): String = person match { case Person(name, _) if name == "Alice" => s"Hello, Alice!" case Person(name, age) => s"Hi, $name! You are $age years old." } val alice = Person("Alice", 30) val bob = Person("Bob", 25) println(greet(alice)) // Output: Hello, Alice! println(greet(bob)) // Output: Hi, Bob! You are 25 years old.
Here, the greet
function pattern matches on the Person
case class, allowing you to handle different cases based on the objects structure.
Nested Case Classes:
Case classes can be nested within other case classes or regular classes. This can be useful for modeling complex data structures. Here is an example of a nested case class:
scalacase class Address(street: String, city: String) case class Contact(name: String, address: Address) val johnsAddress = Address("123 Main St", "New York") val john = Contact("John Doe", johnsAddress) println(john) // Output: Contact(John Doe,Address(123 Main St,New York))
In this example, the Contact
case class contains an Address
case class as one of its fields.
Copying Case Classes:
Case classes support the copy
method, which allows you to create a new instance of the case class with modified values while keeping the original instance unchanged:
scalaval alice = Person("Alice", 30) val olderAlice = alice.copy(age = 35) println(olderAlice) // Output: Person(Alice,35)
The copy
method provides a convenient way to create modified copies of case class instances.
Case classes are commonly used for representing data structures in Scala due to their simplicity, immutability, and the built-in support for common operations like equality and pattern matching. They are especially useful in scenarios where you want to model data with a clear structure and behavior.