EnumSet alternative in Scala, with persistence backed by Slick
Scala does not provide anything like EnumSet in Java standard library. However, since Scala 2.10, Enumeration.ValueSet is providing toBitMask method. Therefore it is possible to store structures like MySQL's SET type in some database systems supporting only integers.With Slick's lifted embedding, we can have it converting the structure to/from the integer type used in database automatically, utilizing MappedColumnType:// Enumeration definition object Weekday extends Enumeration { val Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday = Value val mapping = MappedColumnType.base[ValueSet, Long](_.toBitMask(0), long => ValueSet.fromBitMask(Array(long))) // not necessarily to be defined here } // Table definition class Timeslot(tag: Tag) extends Table[Weekday.ValueSet, Int](tag, "timeslot") { def weekday= column[Weekday.ValueSet]("weekday")(Weekday.mapping) def hour = column[Int]("hour") def * = (weekday, hour) } In this way, for example, the set of "Tuesday, Thursday and Saturday" will be represented by 42 in the database.By the way, to convert a Enumeration.ValueSet it to a List of String, one can use:(input: Weekday.ValueSet) => input.toList.map(_.toString) To convert a List of String back to a Enumeration.ValueSet:(input: List[String]) => Weekday.ValueSet(input.map(Weekday.withName):_*)