为Scala参数化案例类创建Mongo编解码器

时间:2019-06-13 08:17:26

标签: mongodb scala

让我说一个案例类:

final case class Question[+A <: AnswerType](title: List[QuestionLocale],
                                            answers: List[A],
                                            id: UUID)

对于每种类型的AnswerType,我需要为Question写一个mongo编解码器,即

final case class MultipleChoiceText(answers: List[String],
                                    correct: Boolean,
                                    id: UUID) extends AnswerType

Mongo宏Macros.createCodecProviderIgnoreNone[A]不起作用 为Question[MultipleChoiceText]

我所做的是创建自己的自定义编解码器:

class QuestionCodecProvider[A <: AnswerType: ClassTag] extends CodecProvider {

    private val questionct: Class[Question[A]] =
      implicitly[ClassTag[Question[A]]].runtimeClass.asInstanceOf[Class[Question[A]]]


    override def get[T](clazz: Class[T], registry: CodecRegistry): Codec[T] = {
      if (questionct.isAssignableFrom(clazz)) {
        new DocumentCodec(registry).asInstanceOf[Codec[Question[A]]]
      }

      null
    }
  }

当前返回错误:

2019-06-13T07:50:16,397Z - ERROR - Can't find a codec for class com.example.
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.example.

任何帮助将不胜感激。

0 个答案:

没有答案