I have following code snippet:

val serializedClasses: List[MongoMetaRecord[MongoRecord[_]]] = List(User, Email)

Unfortunately I can't get exact type info from the elements and following code fails:

serializedClasses.map(c => new RecordSerializer(c))

[error] JsonFormats.scala:19: inferred type arguments [_$1] do not conform to class RecordSerializer's type parameter bounds [T <: net.liftweb.mongodb.record.MongoRecord[T]]
[error]   implicit val jsonformats = DefaultFormats + (new ObjectIdSerializer)  + (new RecordSerializer(DirectMessage)) + (new RecordSerializer(User)) ++ serializedClasses.map(c => new RecordSerializer(c))

Here is RecordSerializer.scala

object RecordSerializer {
  def apply[T <: MongoRecord[T]](meta: MongoMetaRecord[T]) = new RecordSerializer(meta)
}

class RecordSerializer[T <: MongoRecord[T]](meta: MongoMetaRecord[T]) extends Serializer[MongoRecord[T]] {

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), MongoRecord[T]] = {
case (TypeInfo(clazz, parametrizedType), json: JValue) if(JsonFormats.serializedClassesNames.contains(clazz.getSimpleName)) => {
  meta.fromJValue(json).openOr(throw new MappingException("Couldn't convert"))
    }
  }

  def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
    case rec: MongoRecord[_] => rec.asJValue
  }
}
有帮助吗?

解决方案

I'm not clear on what the question is here. How to get it to compile? RecordSerializer takes a typed MongoRecord and your List does not capture the type of its items. If you want to get this to work you'll either need to capture the record types (you could use an HList like the one provided by Shapeless to capture the type of each item) or you'll need to rewrite your RecordSerializer so that it gets it's type information from the record at runtime only and isn't dependent on knowing a compile time type.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top