Case objects vs Enumerations in Scala

Scala | Case objects vs Enumerations: Here, we will see the difference between case objects and Enumerations in Scala.
Submitted by Shivang Yadav, on December 26, 2020

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 in Scala

// 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 in Scala

// 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 in Scala

  • Case objects are more flexible than enumeration when it comes to pattern matching.
  • In enumeration, iterating over all instances is not possible. But in case of case class overheads are required.
  • Enumerations are just a set of constants and once added all values are constant and only some limited methods are provided.




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.