Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active May 25, 2017 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frgomes/da098c2f10a08440f5de to your computer and use it in GitHub Desktop.
Save frgomes/da098c2f10a08440f5de to your computer and use it in GitHub Desktop.
Scala - Enumerations made easy... well... more or less
// THIS IS Scala 2.11
// see: https://github.com/d6y/enumeration-examples
object Status {
sealed abstract class enum(val id: Int, val name: String) extends Ordered[enum] {
def compare(that: enum) = this.id - that.id
}
case object Starting extends enum(0, "Starting")
case object Running extends enum(1, "Running")
case object Finished extends enum(2, "Finished")
val values = Seq(Starting, Running, Finished)
}
//-------------------------------------------------------------------------------------------
// THIS IS SCALA 2.13
// see: https://github.com/scala/scala/pull/5352
@enum
sealed trait Toggle
case object ON extends Toggle
case object OFF extends Toggle
//-------------------------------------------------------------------------------------------
// THIS IS enum using macros (quasiquotes)
// see: https://github.com/frgomes/poc-scalameta/blob/master/macros/src/main/scala/enum.scala
@frgomes
Copy link
Author

frgomes commented Feb 24, 2015

This is how you can use it:

def happyEnding(status: Status.enum): String =
  if(status == Status.Finished) "happy end" else "not yet"

@DavidDudson
Copy link

I don't like the Status.enum bit. I suggest instead of the abstract class being an inner class of the object. Make it an actual class of the object. I'd also make a trait Enum and extend it but maybe that's just me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment