2

What's the naming convention for a Scala enumeration type? For example, in the below code:

object EventType extends Enumeration {
    type EventType = Value

    val Registered = Value("Registered")
    val Started = Value("Started")
}

/**
 * The event that fires under specific life cycle
 *
 * @param eventType the [[EventType.EventType]]
 */
 case class Event(eventType: EventType.EventType)

The above code follows the same style as described in the Scala doc. The question here is you can see the name of "EventType.EventType" is quite redundant and also quite strange when compared with enum definitions in other languages like Java or C#.

So I'm wondering if there is any recommended naming style to improve the readability?

Thanks in advance.

XuChu LIU
  • 238
  • 3
  • 11
  • You might already be aware of this but a lot of scala programmers avoid the Enumeration class and instead use a sealed base type and case objects for the possible values. If you are interested you can read more in the answers of this question: http://stackoverflow.com/questions/1321745/how-to-model-type-safe-enum-types – johanandren Jun 03 '15 at 15:08
  • Really appreciate your comment. I learnt a lot from this thread – XuChu LIU Jun 06 '15 at 09:41

1 Answers1

1

To shorten it you can use import with an underscore to import everything from the object EventType. So instead of import EventType you would use import EventType._. Here is an example:

scala> object EventType extends Enumeration {
     |     type EventType = Value
     |
     |     val Registered = Value("Registered")
     |     val Started = Value("Started")
     | }
defined object EventType

scala> object Test {
     | import EventType._
     |
     | case class Event(eventType: EventType)
     | }
defined object Test

Things might seem confusing because EventType is the name of the object and EventType.EventType is the type of the enum. So if you use it this way:

EventType.Registered

then in this case it's the name of the object, not the type. On contrary, here:

case class Event(eventType: EventType)

it's the name of the type, i.e. the one defined with type EventType.

If you want to avoid confusion you can give a different name to the type:

scala> object Events extends Enumeration {
     |           type EventType = Value
     |           val Registered = Value("Registered")
     |           val Started = Value("Started")
     | }
defined object Events
scala> object Test {
     | import Events._
     | case class Event(eventType: EventType)
     | val a = Event(Registered)
     | }
defined object Test
yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
  • Thanks for the reply. However this is somehow tricky.... The "import" does not solve the readability issue: there's EventType.Registered and EventType.Started which make others think the "EventType" itself is the "enum" type, but in the Scala world, the "EventType.EventType" is in fact the real type. – XuChu LIU Jun 03 '15 at 06:38