What are Case Objects?
Case objects in Scala are instances of case class which is a regular class with an added pattern-matching feature. A case object is like an object, but just like a case class has more features than a regular class, a case object has more features than a regular object.
Its features include:
- It’s serializable.
- It has a default hashCode implementation.
- It has an improved toString implementation.
Because of these features, case objects are primarily used in two places (instead of regular objects):
- When creating enumerations.
- When creating containers for “messages” that you want to pass between other objects (such as with the Akka actors library).
Syntax:
caseObjName = caseClassName(parameter_values)
Example:
Program to illustrate the creation of case objects in Scala:
// Creating a Case Class
case class student(name: String, standard: Int, marks: Int, result: String )
object myObject {
def main(args: Array[String]) {
// Creating a case Object
val student1 = student("Prem", 10, 89, "A+")
println("Case Object: " + student1)
}
}
Output:
Difference between Case Objects vs Enumerations in Scala
Scala offers multiple constructs for representing a fixed set of values, among which case objects and enumerations stand out. While both serve similar purposes, they have distinct characteristics and use cases. In this article, we’ll explore the differences between case objects and enumerations in Scala, along with their respective advantages and use cases.
Contact Us