Skip to content

Enumerations

christophercurrie edited this page Apr 12, 2013 · 2 revisions

Introduced in Jackson Scala Module 2.2

Enumerations in Scala can be tricky. The Scala documentation recommends declaring them in the form:

object Weekday extends Enumeration {
  type Weekday = Value
  val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}

This has two challenges to overcome:

  1. Enumeration values have the Scala type of Weekday#Value, since Value is an instance-scoped abstract class. However, JVM erasure reduces all of these to the same runtime type, and the type of the enclosing class is lost.

  2. Scala does not allow code to access the class of the singleton object instance at compile time; classOf[Weekday.type] does not compile. Type tricks have to be employed to construct a compile-time proxy.

Solution: in brief

class WeekdayType extends TypeReference[Weekday.type]
case class WeekdayHolder(@JsonScalaEnumeration(classOf[WeekdayType]) weekday: Weekday.Weekday)
Clone this wiki locally