ADT编解码器无法编译

时间:2018-01-02 10:34:12

标签: mongodb scala

我正在使用scala驱动程序使用mongodb进行IO操作。我的scala版本为2.11.11,mongo db驱动程序为2.2.0

我以关于ADT的文档为例:

sealed class Tree
case class Branch(b1: Tree, b2: Tree, value: Int) extends Tree
case class Leaf(value: Int) extends Tree

val codecRegistry = fromRegistries( fromProviders(classOf[Tree]), DEFAULT_CODEC_REGISTRY )

此代码未编译。

No known subclasses of the sealed class
[error]     val codecRegistry = fromRegistries( fromProviders(classOf[Tree]), DEFAULT_CODEC_REGISTRY )
[error]                                                              ^
[error] knownDirectSubclasses of Tree observed before subclass Branch registered
[error] knownDirectSubclasses of Tree observed before subclass Leaf registered

我错过了什么吗?

更新

下面是我要做的一个完整的例子。

build.sbt

name := "mongodb-driver-test"

version := "1.0"

scalaVersion := "2.11.11"

libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "2.2.0"

档案Models.scala

import org.mongodb.scala.bson.codecs.{DEFAULT_CODEC_REGISTRY, Macros}
import org.bson.codecs.configuration.CodecRegistries.{fromProviders, fromRegistries}

/**
  * Created by alifirat on 02/01/18.
  */


object Models {

  sealed class Tree
  case class Branch(b1: Tree, b2: Tree, value: Int) extends Tree
  case class Leaf(value: Int) extends Tree

  val treeCodec = Macros.createCodecProvider[Tree]()

  val treeCodecRegistry = fromRegistries( fromProviders(treeCodec), DEFAULT_CODEC_REGISTRY )

}

然后,就这样做:

sbt compile

你会得到:

[error]   val treeCodec = Macros.createCodecProvider[Tree]()
[error]                                                   ^
[error] knownDirectSubclasses of Tree observed before subclass Branch registered
[error] knownDirectSubclasses of Tree observed before subclass Leaf registered
[error] three errors found
[error] (compile:compileIncremental) Compilation failed

如果我将scala版本更改为2.12.0,我在编译时没有任何错误......

1 个答案:

答案 0 :(得分:1)

我正在使用驱动程序版本2.6.0和Scala版本2.12.8,仍然遇到相同的问题。

我的解决方法是删除该密封类前面的关键字sealed,进行编译,放回原处,然后再次进行编译。但这很麻烦。