Created
April 3, 2017 21:17
-
-
Save davegurnell/3b098c8ee4a725edd4990acf34493ee5 to your computer and use it in GitHub Desktop.
HtmlWriter type class example
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
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