Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Scala Enumerations in Classes

Tags:

enums

scala

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.

like image 365
sudom82 Avatar asked Jan 20 '26 10:01

sudom82


1 Answers

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)

For more info about sealed traits see this SO q&a

like image 181
Alvaro Carrasco Avatar answered Jan 23 '26 20:01

Alvaro Carrasco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!