Forked from aris-vlasakakis-ck/ListOfTypeClasses.scala
Last active
June 20, 2017 20:49
-
-
Save hobwekiva/6250e3ac9d06ee244f348e4a46d197e8 to your computer and use it in GitHub Desktop.
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 Instance[TC[_]] { | |
type Type | |
def value: Type | |
def typeclass: TC[Type] | |
} | |
object Instance { | |
implicit def apply[A, TC[_]](a: A)(implicit A: TC[A]): Instance[TC] = new Instance[TC] { | |
type Type = A | |
val value = a | |
val typeclass = A | |
} | |
} | |
case class Dog() | |
case class Cat() | |
case class Human() | |
trait Talks[A] { | |
def talk(x: A): String | |
} | |
implicit val dogTalks = new Talks[Dog] { | |
def talk(x: Dog): String = "gav gav" | |
} | |
implicit val catTalks = new Talks[Cat] { | |
def talk(x: Cat): String = "niao niao" | |
} | |
implicit val humanTalks = new Talks[Human] { | |
def talk(x: Human): String = "awesome dude" | |
} | |
implicit class TalksSyntax[A](value: A) { | |
def talk(implicit T: Talks[A]): String = T.talk(value) | |
} | |
def listTalk(l: List[Instance[Talks]]): List[String] = { | |
l.map { i => | |
implicit val tc: Talks[i.Type] = i.typeclass | |
i.value.talk // or i.typeclass.talk(i.value) without the implicit | |
} | |
} | |
val h = Human() | |
h.talk | |
val c = Cat() | |
c.talk | |
val d = Dog() | |
d.talk | |
listTalk(List(h, h, h)) | |
listTalk(List(h, c, d)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment