Skip to content

Instantly share code, notes, and snippets.

@tadjik1
Created March 21, 2017 10:11
Show Gist options
  • Save tadjik1/92550407bbff200dc212f42b26806880 to your computer and use it in GitHub Desktop.
Save tadjik1/92550407bbff200dc212f42b26806880 to your computer and use it in GitHub Desktop.
small example of polymorphic encoders
trait Encoder[From] {
type To
def encode(from: From): To
}
object Encoder {
type Aux[From, To0] = Encoder[From] {
type To = To0
}
implicit def compose[A, B, C](implicit e1: Encoder.Aux[A, B], e2: Encoder.Aux[B, C]): Encoder.Aux[A, C] =
new Encoder[A] {
type To = C
override def encode(from: A): C = e2.encode(e1.encode(from))
}
implicit val intToBooleanEncoder = new Encoder[Int] {
type To = Boolean
override def encode(from: Int): Boolean = true
}
implicit val booleanToStringEncoder = new Encoder[Boolean] {
type To = String
override def encode(from: Boolean): String = "hello"
}
}
def print[T, R](t: T)(implicit p: Encoder.Aux[T, R]): R = p.encode(t)
print(10) // true
print(true) // hello
print[Int, String](10) // hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment