It became common knowledge that built-in Scala Enumeration
class is both awkward in design and unhandy in usage.
There's a good reason then to introduce custom library to model enumerations.
com.asavelyev.enums.CaseEnum
is a type class representing sealed hierarchy with a single ancestor (trait or class)
and a set of [case] object
s deriving from it. We will call such objects members.
The toString
representation of a member is considered it's unique key within a given CaseEnum
.
The recommended way of arising CaseEnum
instances is
not manual instantiation, but rather having the companion object of the hierarchy root type extend
helper CaseEnumCompanion
. For example:
sealed trait Color
object Color extends CaseEnumCompanion[Color] {
case object Red extends Color
case object Green extends Color
case object Blue extends Color
}
All the members should be statically accessible objects, so the following enum will fail:
sealed trait Color
object Color extends CaseEnumCompanion[Color] {
case object Red extends Color
case object Green extends Color
case object Blue extends Color
case class Other(r: Int, g: Int, b: Int)//Will fail the companion initialization!
}
The number of goodies provided with in CaseEnum includes:
- Implicit resolution helper:
val colorEnum: CaseEnum[Color] = CaseEnum[Color]
- Getting all the members:
val allColors: Seq[Color] = CaseEnum[Color].all // Set(Red, Green, Blue)
- Getting member by it's
toString
val allColors: Seq[Color] = CaseEnum[Color].fromString("Red")// Some(Red)
If we consider separately defined modules, this is also:
- Implicit Argonaut codecs derivation for enums in
case-enum-argonaut
.
import com.asavelyev.enums.argonautcodec._
case class Car(color: Color)
object Car {
val argonautCodec = casecodec1(apply, unapply)("color")//enum codec derived automatically
}
- Slick enum mapping for string columns in
case-enum-slick