Created
December 15, 2023 22:20
-
-
Save Moverr/9b9b46aab55ac2ef1f22c4e99b9389db to your computer and use it in GitHub Desktop.
Json writer emulating type classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed trait json | |
final case class jsString(get: String) extends json | |
final case class jsObject(get: Map[String, json]) extends json | |
final case class jsNumber(get: Double) extends json | |
case object jsNull extends json | |
trait JsonWriter[A] { | |
def write(value: A): json | |
} | |
// the instances | |
final case class Person(name: String, email: String) | |
object jsonWriterInstances { | |
implicit val stringWriter: JsonWriter[String] = new JsonWriter[String] { | |
def write(value: String): json = { | |
jsString(value) | |
} | |
} | |
implicit val personWriter: JsonWriter[Person] = | |
new JsonWriter[Person] { | |
def write(value: Person): json = { | |
jsObject( | |
Map( | |
"name" -> jsString(value.name), | |
"email" -> jsString(value.email) | |
) | |
) | |
} | |
} | |
} | |
object json { | |
def toJson[A](value: A)(implicit w: JsonWriter[A]): json = | |
w.write(value) | |
} | |
json.toJson("Rogers")(jsonWriterInstances.stringWriter) | |
val pp = Person("movers name", "[email protected]") | |
json.toJson(pp)(jsonWriterInstances.personWriter) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment