Scala: Enum Creation Examples

Enum is used for creating a group of constants like the days of week, colors and etc.

In this post, I am going to show how to create enums in Scala.

There are two ways,
1. Using Scala Enumeration
2. Using Scala Traits

Using Scala Enumeration

Scala has Enumerations class which can be extended to create an Enum. Check the below example.


object ScalaEnumObject {

  def main(args: Array[String]) {
    println("Event:")
    Event.values foreach println
  }
  //Extends Enumeration class
  object Event extends Enumeration {
    type Event = Value
    val CREATE, READ, UPDATE, REMOVE = Value
  }
}

The output looks below,


Event:
CREATE
READ
UPDATE
REMOVE

Using Scala Traits
We can use Trait to create Enums. Trait is similar to Java interface. So we can create a Trait and then create the case object which extends that Trait for each Enum values.

Check the below example.


object ScalaEnumObject {

  def main(args: Array[String]) {
    println("Directions:")
    val directions = List(EAST,WEST,SOUTH,NORTH)
    directions.foreach(direction => println (direction.name))
  }

   //Using Trait
  sealed trait Direction {
    def name: String
  }

  case object EAST extends Direction {
    val name = "E"
  }

  case object WEST extends Direction {
    val name = "W"
  }

  case object SOUTH extends Direction {
    val name = "S"
  }

  case object NORTH extends Direction {
    val name = "N"
  }
}

The output looke below,


Directions:
E
W
S
N

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s