lloydmeta / enumeratum

A type-safe, reflection-free, powerful enumeration implementation for Scala with exhaustive pattern match warnings and helpful integrations.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Circe encoding seems broken

ticofab opened this issue · comments

scala 2.13.1
circe 0.12.3
enumeratum 1.5.15
enumeratumCirce 1.5.23
sbt 1.3.9
intellij idea 2020.1

It seems to me that automatic serialization of enums is broken.

class SerializationTest extends AnyWordSpec with Matchers {

  import enumeratum._

  sealed trait TestEnum extends EnumEntry

  case object TestEnum extends Enum[TestEnum] with CirceEnum[TestEnum] {
    case object ValueOne extends TestEnum
    case object ValueTwo extends TestEnum
    val values: IndexedSeq[TestEnum] = findValues
  }

  "An enum" should {
    "Be encoded correctly" in {
      val value = TestEnum.ValueOne
      val json = value.asJson
      json shouldBe "ValueOne"
    }
  }
}

This test will fail and json will be {\n \n}. Would be awesome if someone can validate this behaviour.

Interestingly, if I add to the above

case class A(ac: TestEnum)

// and later in the test
val a = A(TestEnum.ValueTwo)
val jsonAStr = a.asJson.noSpaces // works! {"ac":"ValueTwo"}

The value of ac is rendered properly.

commented

Can you create a Scastie reproducing this ? https://scastie.scala-lang.org

Thanks for looking at this. I've been trying to use scastie but I am unable to find circe-generic or circe-core in the libraries or even enumeratum 😕 ScalaFiddle doesn't support enumeratum. If you have any tips, I'm happy to follow.

commented

In Build Settings, you can fully customise the build by adding the following under Extra Sbt Configuration

libraryDependencies ++= Seq(
  "io.circe"      %% "circe-generic" % circeVersion
)
commented

I think this is a combination of:

  1. Using the member directly, causing it to resolve the object type (ValueOne.type): using a type annotation fixes this
  2. Using the auto codec derivation

Here is a fixed version: https://scastie.scala-lang.org/lloydmeta/1ZP27Mb9TWy4OP77goDQnA

Thanks for checking @lloydmeta . I tried again with my version, the only thing I had to change to make it work was adding the type explicitly: val value: TestEnum = TestEnum.ValueOne instead of val value = TestEnum.ValueOne. I'm not sure what you want to do with this issue -- it can probably be closed but I leave this to you :) Cheers.