Created
January 19, 2016 16:44
-
-
Save julien-truffaut/b36f99bc37f6428e8696 to your computer and use it in GitHub Desktop.
Typeclass example
This file contains hidden or 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
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