Skip to content

Instantly share code, notes, and snippets.

@julien-truffaut
Created January 19, 2016 16:44
Show Gist options
  • Save julien-truffaut/b36f99bc37f6428e8696 to your computer and use it in GitHub Desktop.
Save julien-truffaut/b36f99bc37f6428e8696 to your computer and use it in GitHub Desktop.
Typeclass example
package bilberry.snippet
import scalaz.syntax.functor._
trait MyShow[A] {
def show(a: A): String
}
object MyShow {
def apply[A](implicit ev: MyShow[A]): MyShow[A] = ev // summon the implicit using syntax MyShow[X]
def show[A](f: A => String): MyShow[A] = // smart constructor
new MyShow[A] {
def show(a: A): String = f(a)
}
implicit def syntax[A: MyShow](a: A): ShowOps[A] = ShowOps(a) // pimp any a with an instance of MyShow
// define instances here
implicit val stringShow: MyShow[String] = show(identity)
implicit val intShow: MyShow[Int] = show(_.toString)
implicit def setShow[A: MyShow]: MyShow[Set[A]] =
show((set: Set[A]) => set.toList.map(_.myShow).mkString("(", ", ", ""))
}
case class ShowOps[A](a: A)(implicit ev: MyShow[A]){
def myShow: String = ev.show(a)
}
case class Person(name: String, age: Int)
object Person {
implicit val myShow: MyShow[Person] = MyShow.show(p => s"Person(name: ${p.name}, age: ${p.age})")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment