sudom82 sudom82 - 2 months ago 6
Scala Question

How to use Scala Enumerations in Classes

I'm learning Scala and am trying to get a simple enum setup for a project. I've checked a few examples and none seem to fit, all of the examples in the Scala documentation and on StackOverflow are for enums inside objects, not classes. I'm getting an IDE warning that I don't understand. I'm coming from a beginner Java background into Scala, which may be the cause of my confusion.

Here's the code:

class Car(maxSpeed: Integer) {

// Enums
object CarType extends Enumeration {
type CarType = Value
val PERIPHERAL, COMPUTER, EMPTY = Value
}
import CarType._

// Fields
val repeated: CarType
}


When I mouse over the class name, I can see this Intellij warning:


Class 'Car' must either be declared abstract or implement abstract member 'typed: Car.this.CarType.CarType' in 'Car'


I'm not sure why it wants me to implement my variable, and the class is not intended to be abstract. I'd like to use Enums similarly to how they are used in Java.

Answer

Move the enumeration outside the class:

// Enums
object CarType extends Enumeration {
  type CarType = Value
  val PERIPHERAL, COMPUTER, EMPTY = Value
}
class Car(maxSpeed: Integer) {
  import CarType._

  // Fields
   val repeated: CarType
}

Or move it to a companion object:

class Car(maxSpeed: Integer) {
  import Car.CarType._

  // Fields
   val repeated: CarType
}

object Car {
  object CarType extends Enumeration {
    type CarType = Value
    val PERIPHERAL, COMPUTER, EMPTY = Value
  }
}

The problem is that things defined inside of a class are scoped to the the instance of that class (unlike some other languages).

That said, I recommend using algebraic data types instead of enums:

sealed trait CarType
object CarType {
  case object Peripheral extends CarType // strange choice of names
  case object Computer extends CarType
  case object Empty extends CarType
}

case class Car(maxSpeed: Int, carType: CarType)
Comments