Skip to content

Instantly share code, notes, and snippets.

@ivportilla
Last active July 26, 2017 16:01
Show Gist options
  • Save ivportilla/0c4c9ceeb526e46d9d4cf36333881086 to your computer and use it in GitHub Desktop.
Save ivportilla/0c4c9ceeb526e46d9d4cf36333881086 to your computer and use it in GitHub Desktop.
/* Data definition */
trait DocumentInfo {
val title: String
}
case class D1(title: String, content: String) extends DocumentInfo
case class D2(title: String, count: Int) extends DocumentInfo
/* -------------- */
/* Type Class */
trait DocumentWriter[A] {
def write(document: A): String
}
object WriterInstances {
implicit val d1Writer = new DocumentWriter[D1] {
def write(document: D1): String = s"DocumentInfo D1 -> ..."
}
implicit val d2Writer = new DocumentWriter[D2] {
def write(document: D2): String = s"DocumentInfo D2 -> ..."
}
}
object DocumentSe {
def write[A](document: A)(implicit w: DocumentWriter[A]): String =
w.write(document)
}
/* --------------- */
object Test {
import WriterInstances._
def generalF(d: DocumentInfo): String = DocumentSe.write(d)
val d1 = D1("title1", "asd")
val d2 = D2("title2", 2)
println(generalF(d1))
println(generalF(d2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment