Greg Greg - 1 month ago 11
Scala Question

Can I use Enumerations as type parameters in Scala?

I'd like to use an Enumeration as a type parameter by the compiler is giving me grief.

object VehicleClass extends Enumeration {
type VehicleClass = Value
val Land, Air, Sea = Value
}
import VehicleClass._

trait Vehicle[K <: VehicleClass] { val kind: K }
case class Car(passengers: Int) extends Vehicle[Land] { val kind: Land }


Compiler complains:

[error] /Users/me/test/scala/co.blocke.scalajack/json/test.misc/Greg.scala:18: not found: type Land
[error] case class Car(passengers: Int) extends Vehicle[Land] { val kind: Land }
[error] ^
[error] /Users/me/test/scala/co.blocke.scalajack/json/test.misc/Greg.scala:18: not found: type Land
[error] case class Car(passengers: Int) extends Vehicle[Land] { val kind: Land }
[error] ^


How can this be done?

Answer

You can write

case class Car(passengers: Int) extends Vehicle[Land.type] { 
  val kind: Land.type = Land 
}

Land.type is the singleton type of Land, i.e. the type whose only value is Land (not including null).

Comments