Timo Westkämper
Timo Westkämper

Reputation: 22190

Define Enumeration object and value class on same level

Is it possible to declare an Enumeration object and class on the same level in Scala?

I started with this, but I am not sure what is the best way to register the instances.

object Gender extends Enumeration {
  val MALE = new Gender(0)
  val FEMALE = new Gender(1)
}

class Gender(val id: Int) extends Gender.Value {

}

The motivation for this is that I don't want to refer to the enum class as Gender.Gender, but Gender.

Upvotes: 1

Views: 481

Answers (1)

Owen
Owen

Reputation: 39366

This works:

object Gender extends Enumeration {
    val male   = new Gender
    val female = new Gender

    class Sneaky extends Val(nextId, null)
}

class Gender extends Gender.Sneaky

> println(Gender.values)
Gender.ValueSet(male, female)

However I do not really feel good about it. I think it would be better either to make a type alias (if you can at this scope):

object Gender extends Enumeration {
    ...
}

type Gender = Gender.Value

Or import the type before you use it:

object Gender extends Enumeration {
    val male, female = Value

    type Gender = Value
}

import Gender._
val x: Value = male

(Or, if you can, use case classes).

Upvotes: 3

Related Questions