CodexBloom - Programming Q&A Platform

How to handle type mismatches when using shapeless to create a generic serializer in Scala?

šŸ‘€ Views: 567 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-04
scala shapeless circe Scala

Does anyone know how to I'm reviewing some code and I'm sure I'm missing something obvious here, but I'm trying to implement a generic serializer using the shapeless library in Scala, but I'm running into issues with type mismatches. My goal is to serialize case classes into JSON strings, and I'm using the `Generic` type class from shapeless to achieve this. However, when I attempt to serialize a case class, I get the following behavior: ``` behavior:(15, 29) type mismatch; found : String required: List[String] ``` Here's the code I have so far: ```scala import shapeless._ import shapeless.ops.hlist._ import io.circe.{Encoder, Json} import io.circe.syntax._ case class Person(name: String, age: Int) trait JsonSerializer[T] { def serialize(value: T): Json } object JsonSerializer { implicit def hnilSerializer: JsonSerializer[HNil] = new JsonSerializer[HNil] { def serialize(value: HNil): Json = Json.obj() } implicit def hconsSerializer[H, T <: HList]( implicit headEncoder: Encoder[H], tailEncoder: JsonSerializer[T] ): JsonSerializer[H :: T] = new JsonSerializer[H :: T] { def serialize(value: H :: T): Json = { val head = headEncoder(value.head) val tail = tailEncoder.serialize(value.tail) tail.asObject.map(_.add("head", head)).getOrElse(tail) } } implicit def caseClassSerializer[A, R <: HList]( implicit gen: Generic.Aux[A, R], serializer: JsonSerializer[R] ): JsonSerializer[A] = new JsonSerializer[A] { def serialize(value: A): Json = serializer.serialize(gen.to(value)) } } implicit val personEncoder: Encoder[Person] = Encoder.forProduct2("name", "age")(p => (p.name, p.age)) val person = Person("Alice", 25) val jsonSerializer = implicitly[JsonSerializer[Person]] val json = jsonSerializer.serialize(person) println(json) ``` I suspect that the question lies in how I’m trying to handle the serialization of the head of the HList, but I'm not sure how to fix it. In particular, I think the scenario arises in this line: ```scala val head = headEncoder(value.head) ``` Could anyone provide some guidance on how to resolve this type mismatch? Is there a better way to structure the `JsonSerializer` implementation to handle different types correctly? I'm currently using Scala 2.13.6 and shapeless 2.3.7. My development environment is Ubuntu. Am I missing something obvious? For context: I'm using Scala on macOS. I'd really appreciate any guidance on this. I recently upgraded to Scala 3.10. What's the best practice here? The stack includes Scala and several other technologies. Any examples would be super helpful. I'm working with Scala in a Docker container on macOS.