×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Case objects vs Enumerations in Scala

By IncludeHelp Last updated : November 07, 2024

Case Objects

Case objects in Scala are instances of case class which is a regular class with an added pattern matching feature.

Syntax

caseObjName = caseClassName(parameter_values)

Program to illustrate the creation of case objects

// 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:

Case Object: student(Prem,10,89,A+)

Enumeration

Enumeration is a feature in Scala used to define a group of constants.

Syntax

object enum_object extends Enumeration {
    type enum_object = value 
    /// Assigning value 
    val name1 = Value("value")
}

Program to illustrate creation of Enumeration

// Program to illustrate the creation of Enum in Scala...

object Main extends Enumeration { 
    type Main = Value 
    
    val day1 = Value("Sunday") 
    val day2 = Value("Monday") 
    val day3 = Value("Tuesday") 
    val day4 = Value("Wednesday") 
    val day5 = Value("Thursday") 
    val day6 = Value("Friday") 
    val day7 = Value("Saturday") 
    
    def main(args: Array[String]) {
        println("Value of Enum : " + Main.values ) 
    } 
} 

Output:

Value of Enum : Main.ValueSet(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

Difference between Case objects and Enumerations

Here's a difference table comparing Case Objects and Enumerations in Scala:

Feature Case Objects Enumerations
Pattern Matching Flexibility More flexible for pattern matching Limited flexibility
Instance Iteration Supports iterating over all instances Does not support iterating over all instances
Overheads Requires additional case class overheads Minimal overhead, just a set of constants
Value Mutability Values can be extended and manipulated if needed All values are constant once defined
Methods Provided Flexible with additional methods Limited predefined methods

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.