scalaenumscirce

Automatic derivation of Enumeration can't find Encoder


I have a case class like this:

case class Admin(name: String, role: Role)

Role is an Enumeration

object Role extends Enumeration {
  type Role = Value
  val Manager = Value
}

When I try to:

import io.circe.generic.auto._, io.circe.syntax._

val response = Admin("John", Role.Manager).asJson.noSpaces

I get the implicit Encoder not found error.

not enough arguments for method asJson: (implicit encoder: io.circe.Encoder[Admin])io.circe.Json. Unspecified value parameter encoder.

I suppose this error is due Enumeration, so I changed to:

trait Role

object Role {
  object Manager extends Role
}

But this does't work too.

Lastly, I tried:

trait Role

object Manager extends Role

And no success. Can someone help me please? Thanks!


Solution

  • enumeratum-circe enables the following syntax

    object CirceEnumeratumExample extends App {
      import enumeratum._
      import io.circe.generic.auto._, io.circe.syntax._
    
      sealed trait Role extends EnumEntry
      case object Role extends Enum[Role] with CirceEnum[Role] {
        case object Manager  extends Role
        case object User extends Role
        val values = findValues
      }
    
      case class Admin(name: String, role: Role)
      val response = Admin("John", Role.Manager).asJson.noSpaces
      println(response)
    }
    

    which outputs

    {"name":"John","role":"Manager"}
    

    where

    libraryDependencies += "com.beachape" %% "enumeratum" % "1.5.13",
    libraryDependencies += "com.beachape" %% "enumeratum-circe" % "1.5.21"