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