1

This question is related to the first one: Iteration over a sealed trait in Scala?

I have the following sealed trait

/**
 * @author Sebastien Lorber (<i>lorber.sebastien@gmail.com</i>)
 * Date: 02/12/12 - Time: 17:49
 */
sealed trait ResizedImageKey {

  /**
   * Get the dimensions to use on the resized image associated with this key
   */
  def getDimension(originalDimension: Dimension): Dimension

}

object ResizedImageKey {
  val ALL_KEYS: List[ResizedImageKey] = List(Large,Medium,Small,X2)
}

case class Dimension(width: Int,  height: Int)

case object Large extends ResizedImageKey {
  def getDimension(originalDimension: Dimension) = Dimension(1000,1000)
}

case object Medium extends ResizedImageKey{
  def getDimension(originalDimension: Dimension) = Dimension(500,500)
}

case object Small extends ResizedImageKey{
  def getDimension(originalDimension: Dimension) = Dimension(100,100)
}

case object X2 extends ResizedImageKey{
  def getDimension(originalDimension: Dimension) = Dimension(
    width = originalDimension.width * 2,
    height = originalDimension.height * 2
  )
}

This works fine for now. The matter is that I need to be able to use my ResizedImageKey as a key for a map that will be stored in MongoDB with Salat.

I don't think Salat support "sealed trait convertion" right? So should I move to Enumeration, which forces me to do a match / case for the dimensions computations? Or is there any known solution to this problem? Is it possible to create enumeration Value object without extending Enumeration or something?

Thanks

Community
  • 1
  • 1
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419

1 Answers1

3

Salat developer here.

Salat supports case object hierarchies using the @Salat annotation. (I never recommend using enums in Scala - they're dreadful.)

Now... using a case object as the key for a map is actually not something that mongo supports. All map keys in mongo need to be strings.

So what does this map you're trying to persist look like?

prasinous
  • 798
  • 3
  • 6
  • Thanks. It looks like [ImageResizeKey,FileDescriptor] and I'd prefer keep it like that than doing [String,FileDescriptor] if possible. – Sebastien Lorber Dec 04 '12 at 09:10
  • Unfortunately, since MongoDB doesn't support using object as the key to a map, what you can do is persist a list of case classes and convert it to a map as a lazy val inside your case class. Requiring the keys to maps to be strings is an explicit limitation of MongoDB. – prasinous Dec 04 '12 at 16:35