alifirat
alifirat

Reputation: 2937

Codec for ADT do not compile

I'm using the scala driver to make IO operations with mongodb. My scala version is 2.11.11 and the mongo db driver is 2.2.0.

I take the example in documentation about 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 )

This code didn't compile.

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

Did I miss something ?

Update

Below a complete example of what I'm tring to do.

build.sbt

name := "mongodb-driver-test"

version := "1.0"

scalaVersion := "2.11.11"

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

file 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 )

}

Then, just do :

sbt compile

You will get :

[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

If I change the scala version to 2.12.0, I didn't have any errors at compile time ...

Upvotes: 4

Views: 617

Answers (1)

TheOutsider
TheOutsider

Reputation: 63

I'm using driver version 2.6.0 and Scala version 2.12.8 and still get the same problem.

My workaround is to remove the keyword sealed in front of that sealed class, compile, put it back, and then compile again. But it's very cumbersome.

Upvotes: 3

Related Questions