Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Examples of implementing Type Classes in Scala
trait Publishable {
def asWebMarkup: String
}
case class BlogPost(title: String, text: String) extends Publishable {
def asWebMarkup =
"""|<h2>%s</h2>
|<div>%s</div>""".stripMargin format(title, text)
}
class WebPublisher[T <: Publishable] {
def publish(p: T) = println(p.asWebMarkup)
}
val post = new BlogPost("Test", "This is a test post")
val web = new WebPublisher[BlogPost]()
web publish(post)
//////////////////////////////////////////////////////////////////////////////
trait Publishable {
def asWebMarkup: String
}
case class BlogPost(title: String, text: String)
implicit def BlogPostToPublishable(blogPost: BlogPost) = new Publishable {
def asWebMarkup =
"""|<h2>%s</h2>
|<div>%s</div>""".stripMargin format(blogPost title, blogPost text)
}
class WebPublisher[T <% Publishable] {
def publish(p: T) = println(p.asWebMarkup)
}
val post = new BlogPost("Test", "This is a test post")
val web = new WebPublisher[BlogPost]()
web publish(post)
//////////////////////////////////////////////////////////////////////////////
trait Publishable[T] {
def asWebMarkup(p: T): String
}
case class BlogPost(title: String, text: String)
object BlogPostPublisher extends Publishable[BlogPost] {
def asWebMarkup(p: BlogPost) =
"""|<h2>%s</h2>
|<div>%s</div>""".stripMargin format(p title, p text)
}
implicit def Publishable[BlogPost] = BlogPostPublisher
class WebPublisher[T: Publishable] {
def publish(p: T) = println(implicitly[Publishable[T]] asWebMarkup(p))
}
val post = new BlogPost("Test", "This is a test post")
val web = new WebPublisher[BlogPost]()
web publish(post)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment