What is Enumeration?
Enumeration is a feature of Scala that is used to define a group of named constants accessed using the enum name and ids. The enums in Scala work similar to enum in other programming languages like C/C++, Java. The difference is in creation syntax. In Scala, the enum’s are created by extending an abstract class Enumeration.
abstract class Enumeration extends Serializable
This is different from classical enum creation syntax where we would use the keyword enum for creating Enumeration.
Syntax:
object enum_object extends Enumeration {
type enum_object = value
/// Assigning value
val name1 = Value(“value”)
}
Example:
Program to illustrate creation of Enumeration 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")
def main(args: Array[String]) {
println("Value of Enum : " + Main.values )
}
}
Output:
In the above code, we have created an object name Main which is used to create enumeration which contains days of the week. Then we have printed its value in the main method using the println.
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.