Created
August 31, 2025 14:14
-
-
Save sshark/700ac3f717a29ebb5dbca32f72d144d4 to your computer and use it in GitHub Desktop.
Supporting Heterogeneous Types, The Simple (Scala 3) Way. Thanks to https://yanns.github.io/blog/2019/10/18/heterogeneous-types-scala/
This file contains hidden or 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
| enum Json: | |
| case IntJson(value: Int) extends Json | |
| case StringJson(value: String) extends Json | |
| import Json.StringJson | |
| import Json.IntJson | |
| case class AsJson(json: Json) | |
| trait Encoder[A]: | |
| def encode(a: A): Json | |
| object Encoders: | |
| given Encoder[String] with | |
| override def encode(s: String): Json = StringJson(s) | |
| given Encoder[Int] with | |
| override def encode(i: Int): Json = IntJson(i) | |
| object ToAsJson: | |
| given [A: Encoder]: Conversion[A, AsJson] with | |
| def apply(a: A): AsJson = AsJson(summon[Encoder[A]].encode(a)) | |
| def encode(xs: List[AsJson]): List[Json] = xs.map(_.json) | |
| import scala.language.implicitConversions | |
| import Encoders.given | |
| import ToAsJson.given | |
| encode(List("hello", "world", 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment