2014年9月

提起音乐盒,我就想起那个在五华山附近的小店里买的木质的八音盒。

那应当是我小学的时候,似乎那时候那条路上的车还很少。那一家并不明亮的小店应该卖各种木质的小工艺品的。一家三口一起散步的时候我们偶然见到那家店,便在那里买了一个木质的八音盒。

唯一有印象的是,它的声音很安静。

在周末的午后,家里的阳台上照进非常安静的阳光,空气中的点点灰尘在阳光下清晰可见;我在翻箱倒柜找东西的时候,偶然见到那一个木质的音乐盒,把它拿出来放在安静的阳光下,转动发条,听那空灵的声音。

后来以我毁物不倦的本性,它上面的木条和木板被我一块一块弄掉下来,最后的尸骨已不知去向。

可那清澈的声音,却一直留在我脑海里,仿佛代表着最后的童年,久久不肯散去。

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):_*)