I am learning Circe and Scala for a project at work. To explain my issue, start with the following example:
import io.circe.syntax._
object TestDrive extends App {
val labels = Seq("Banana", "Banano", "Grapefruit")
println(labels.asJson)
}
Ok so this outputs:
["Banana","Banano","Grapefruit"]
This is good.
Now I want to make my code a bit more general. I want to write a function that takes in a Sequence, whose elements can be of type AnyVal.
Here is my attempt:
import io.circe.syntax._
import io.circe.Json
object TestDrive extends App {
def f1[T](lst: Seq[T]): Json = {
lst.asJson
}
val labels = Seq("Banana", "Banano", "Grapefruit")
println(f1(labels))
}
This fails because:
could not find implicit value for parameter encoder: io.circe.Encoder[Seq[T]]
Ok so I need to make an implicit value for the encoder because the type T is too general. Here is my second attempt using scala ClassTags:
import io.circe.syntax._
import io.circe.Json
import scala.reflect.ClassTag
object TestDrive extends App {
def f1[T <: AnyVal](lst: Seq[T])(implicit ev: ClassTag[T]): Json = {
lst.asJson
}
val labels = Seq("Banana", "Banano", "Grapefruit")
println(f1(labels))
}
This fails with:
type mismatch;
found : Seq[String]
required: Seq[T]
How do I go about solving this? I read through the Circe docs but I cannot understand how to handle this type of example.
If someone could kindly explain, with a bit of explanation as to how they resolve something like this, it would be much appreciated. I should add I am new to Scala so any explanation would be useful which explains the theory too.
Thanks!