Skip to content

Instantly share code, notes, and snippets.

@skipoleschris
Created September 28, 2011 11:47
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 skipoleschris/1247752 to your computer and use it in GitHub Desktop.
Save skipoleschris/1247752 to your computer and use it in GitHub Desktop.
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