Skip to content

Instantly share code, notes, and snippets.

@davegurnell
Created April 3, 2017 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davegurnell/3b098c8ee4a725edd4990acf34493ee5 to your computer and use it in GitHub Desktop.
Save davegurnell/3b098c8ee4a725edd4990acf34493ee5 to your computer and use it in GitHub Desktop.
HtmlWriter type class example
trait HtmlWriter[A] {
def apply(value: A): String
}
object HtmlWriter {
def apply[A](implicit writer: HtmlWriter[A]): HtmlWriter[A] =
writer
def write[A](value: A)(implicit writer: HtmlWriter[A]): String =
writer.apply(value)
implicit val intWriter: HtmlWriter[Int] =
new HtmlWriter[Int] {
def apply(value: Int): String =
value.toString
}
implicit val booleanWriter: HtmlWriter[Boolean] =
new HtmlWriter[Boolean] {
def apply(value: Boolean): String =
(if(value) "yes" else "no")
}
implicit def listWriter[A](implicit writer: HtmlWriter[A]): HtmlWriter[List[A]] =
new HtmlWriter[List[A]] {
def apply(value: List[A]): String =
"<ul>" + value.map(value => "<li>" + writer.apply(value) + "</li>").mkString + "</ul>"
}
}
object Main extends App {
println(HtmlWriter.write(List(1, 2, 3)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment