Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
enumeration

What is an enumeration in Scala?

Sarvech Qadir

An enumeration is a user-defined data structure that allows users to assign names to ordered integer constants.

Example

Let’s consider the days of the week from Sunday to Saturday to create an enumeration.

{Sun, Mon, Tue, Wed, Thu, Fri, Sat}

In Java or C, we use an enum keyword. However, there are no such criteria in Scala. In Scala, a programmer can use the built-in enumeration class and extend it while creating an object.

Once an enumeration is created, its values should not be modified since that makes it unsafe for use with threads.

Enumeration
Enumeration

Code

In the code below, we have created an enumeration of the days of the week and displayed them one by one.

Since we did not assign specific integer values to each name ourselves, the compiler assigns values starting from 0.

object Main extends Enumeration 
{
    type Main = Value
      
    // Assigning values
    val firstday = Value("Sun") // id 0
    val secondday = Value("Mon") // id 1
    val thirdday = Value("Tue") // id 2
    val fourthday = Value("Wed") // id 3
    val fifthday = Value("Thur") // id 4
    val sixthday = Value("Fri") // id 5
    val seventhday = Value("Sat") // id 6
      
    
    
 def main(args: Array[String])
    {
        println(s"Days of the week = ${Main.values}")

        // Let's try accessing a single day
         println(s"What is fourthday? = ${Main.fourthday}")

         // Let's try accessing a single day
         println(s"What is the id fourthday? = ${Main.fourthday.id}")


    }    
}

RELATED TAGS

scala
enumeration

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring