Circe: Useless compile error while lacking encoder/decoder

Created on 15 Aug 2015  ·  3Comments  ·  Source: circe/circe

If there is no encode for date, then compiler complains

 [error] /home/jilen/workspace/jfc-test/src/main/scala/Foo.scala:26: diverging implicit expansion for type io.circe.Encoder.Secondary[this.Out]
[error] starting with method encodeCaseClass in trait GenericInstances

Is there any chance to improve the error reporting ?

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

import java.util.Date
case class Foo(
  date: Date,
  number: Int,
  str: String)

object App {

  def encodesDate(fmt: String): Encoder[Date] = new Encoder[Date] {
    def apply(a: Date) = {
      val sdf = new java.text.SimpleDateFormat(fmt)
      Json.string(sdf.format(a))
    }
  }



  def main(args: Array[String])  {
    //implicit val DateEncodes = encodesDate("yyyy-MM-dd HH:mm:ss")
    val f = Foo(new Date, 1, "fff")
    println(f.asJson.noSpaces)
  }
}

Most helpful comment

+1 to use implicitNotFound !
To decode and encode date, juest implicit

  implicit val dateTimeEncoder: Encoder[DateTime] = Encoder.instance(a => a.getMillis.asJson)
  implicit val dateTimeDecoder: Decoder[DateTime] = Decoder.instance(a => a.as[Long].map(new DateTime(_)))

Because of date has many format, I suggest that defined it in the documention and don't add a default format in the jfc.

All 3 comments

Yeah, that's a pretty terrible error message—thanks for pointing it out.

The implementation of the generic derivation mechanism will be changing with #30, which I'm hoping to get done tomorrow, so after that dust settles I'll revisit this and #34, since things might be a little different by then. We should be able to use @implicitNotFound in a few places to improve these messages a lot (see for example this message in Finch).

+1 to use implicitNotFound !
To decode and encode date, juest implicit

  implicit val dateTimeEncoder: Encoder[DateTime] = Encoder.instance(a => a.getMillis.asJson)
  implicit val dateTimeDecoder: Decoder[DateTime] = Decoder.instance(a => a.as[Long].map(new DateTime(_)))

Because of date has many format, I suggest that defined it in the documention and don't add a default format in the jfc.

I'm going to go ahead and close this since the following is a huge improvement:

<console>:59: error: could not find implicit value for parameter e: io.circe.Encoder[Foo]
           println(f.asJson.noSpaces)
                     ^

I'm not actually sure there's much additional useful information we could add with @implicitNotFound in this case, apart from maybe a pointer to the docs.

Was this page helpful?
0 / 5 - 0 ratings