0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Custom Codecs

Handle tricky shapes.

Custom Codecs is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

When You Need Custom Codecs

Derivation covers the common case, but sometimes JSON does not mirror your case class: legacy field names, encoded enums, or formats like timestamps.

Then you write a Decoder, an Encoder, or both by hand.

A Decoder from a Cursor

The most explicit way to build a decoder is Decoder.instance, receiving an HCursor.

You navigate fields with downField and as, returning an Either.

import io.circe.Decoder

case class User(name: String, age: Int)
implicit val dec: Decoder[User] = Decoder.instance { c =>
  for {
    n <- c.downField("full_name").as[String]
    a <- c.downField("years").as[Int]
  } yield User(n, a)
}

forProductN Helpers

For straightforward mappings, Decoder.forProduct2 is more concise: list the JSON keys and pass the constructor.

Helpers exist from forProduct1 up through many arguments.

import io.circe.Decoder

implicit val dec: Decoder[User] =
  Decoder.forProduct2("full_name", "years")(User.apply)

An Encoder by Hand

Mirror the decoder with Encoder.instance, building a Json object from your fields.

Or use Encoder.forProduct2 to map back to chosen JSON keys with a single call.

import io.circe.Encoder

implicit val enc: Encoder[User] =
  Encoder.forProduct2("full_name", "years")(u =>
    (u.name, u.age))

Transforming Existing Codecs

You rarely start from zero. map adapts a decoder's output and contramap adapts an encoder's input.

emap is like map but can fail, returning Either[String, A] for validation.

import io.circe.Decoder

case class Age(value: Int)
implicit val dec: Decoder[Age] =
  Decoder[Int].emap { i =>
    if (i >= 0) Right(Age(i)) else Left("negative age")
  }

Codecs for Enums

Sealed traits with case objects model enums. Encode each to a tag string and decode by matching that string back.

emap turns an unknown tag into a clean decoding failure.

sealed trait Role
case object Admin extends Role
case object Guest extends Role

implicit val dec: Decoder[Role] = Decoder[String].emap {
  case "admin" => Right(Admin)
  case "guest" => Right(Guest)
  case other   => Left(s"unknown role: $other")
}

Encoding the Enum Back

Pair the enum decoder with a contramap encoder that renders each case to its tag.

Now the sealed trait round-trips as a plain string in JSON.

import io.circe.Encoder

implicit val enc: Encoder[Role] = Encoder[String].contramap {
  case Admin => "admin"
  case Guest => "guest"
}

Custom Codec for Dates

Circe has no built-in java.time codecs in the core module, so dates are a classic custom-codec case.

Decode and encode through the ISO string format.

import java.time.LocalDate
import io.circe.{Decoder, Encoder}

implicit val dec: Decoder[LocalDate] =
  Decoder[String].map(LocalDate.parse)
implicit val enc: Encoder[LocalDate] =
  Encoder[String].contramap(_.toString)

Bundling into a Codec

When you have both directions, combine them into one Codec[A] with Codec.from(decoder, encoder).

This keeps a single implicit in scope instead of two separate ones.

import io.circe.Codec

implicit val roleCodec: Codec[Role] =
  Codec.from(dec, enc)

Discriminators for ADTs

For sealed hierarchies with data, circe-generic-extras adds a discriminator field instead of a wrapper object.

Configure it once and derive codecs for the whole ADT.

import io.circe.generic.extras._

implicit val cfg: Configuration =
  Configuration.default.withDiscriminator("type")

@ConfiguredJsonCodec sealed trait Shape
@ConfiguredJsonCodec case class Circle(r: Double) extends Shape

Implicit Scope and Priority

A hand-written implicit codec takes precedence over derivation as long as it is in scope. Put it in the companion object so it is always found.

Avoid importing both auto._ and a manual instance for the same type to prevent ambiguity.

Quick Check

Test your understanding of custom codecs.

Recap

Custom codecs handle JSON that does not match your types. Build them with Decoder.instance, forProductN, or transform existing ones via map, contramap, and emap.

Enums and dates are common cases; bundle directions with Codec.from, and use discriminators for ADTs.

Frequently asked questions

Is the “Custom Codecs” lesson free?

Yes — the full text of “Custom Codecs” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.

What will I learn in “Custom Codecs”?

Handle tricky shapes. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Custom Codecs” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Parsing JSON
  2. Decoding into Case Classes
  3. Encoding to JSON
  4. Custom Codecs
← Back to Scala for Backend Engineering & Functional Programming