Skip to content

Instantly share code, notes, and snippets.

@wolfendale
Last active June 23, 2017 14:13
Show Gist options
  • Save wolfendale/ad3553642b61fee2774101f24ee4b6de to your computer and use it in GitHub Desktop.
Save wolfendale/ad3553642b61fee2774101f24ee4b6de to your computer and use it in GitHub Desktop.
Typeclass Example
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)
}
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