Last active
June 23, 2017 14:13
-
-
Save wolfendale/ad3553642b61fee2774101f24ee4b6de to your computer and use it in GitHub Desktop.
Typeclass Example
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
package wolfendale | |
case class Person(name: String) | |
object Typeclasses extends App { | |
import Show.Showable | |
val tuple = (Person("Michael"), Person("Not Michael")) | |
val tuple2 = (Person("Michael"), (Person("Not Michael"), Person("Foo"))) | |
println(tuple.show) | |
} |
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
package wolfendale | |
trait Show[A] { | |
def show(a: A): String | |
} | |
object Show { | |
implicit val personInstance: Show[Person] = new Show[Person] { | |
override def show(a: Person): String = a.name | |
} | |
implicit def tupleInstances[A : Show, B : Show]: Show[(A, B)] = new Show[(A, B)] { | |
override def show(a: (A, B)): String = s"(${a._1.show}, ${a._2.show})" | |
} | |
implicit class Showable[A : Show](a: A) { | |
def show: String = | |
implicitly[Show[A]].show(a) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment