Frank
Frank

Reputation: 4461

Scala: what if I used class instead of object for an Enumeration?

Would anything bad happen if I wrote:

class TaskType extends Enumeration {
  type TaskType = Value
  val LINEAR_REGRESSION, POISSON_REGRESSION, LOGISTIC_REGRESSION, SMOOTHED_HINGE_LOSS_LINEAR_SVM, NONE = Value
};

The IDE and compiler seem fine with it. It gets me out of some import TaskType._ which I have to insert if TaskType is an object rather than a class.

Upvotes: 1

Views: 24

Answers (1)

maasg
maasg

Reputation: 37435

It defeats the purpose of having an enumeration as a set of unique stable identifiers.

To use members of a class, we need an instance. The members of each instance will be different. In practical terms, LINEAR_REGRESSION instantiated in some part of the system will not be the same as a LINEAR_REGRESSION instantiated somewhere else.

eg.:

class TaskType extends Enumeration {
  type TaskType = Value
  val LINEAR_REGRESSION, POISSON_REGRESSION, LOGISTIC_REGRESSION, SMOOTHED_HINGE_LOSS_LINEAR_SVM, NONE = Value
}
val instance = new TaskType
val otherInstance = new TaskType


import instance._

val lr = LINEAR_REGRESSION

val lr2 = otherInstance.LINEAR_REGRESSION


lr == lr2
// false

Upvotes: 2

Related Questions