Skip to content

Instantly share code, notes, and snippets.

@abdheshkumar
Created August 10, 2017 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdheshkumar/b8ebca629bafe0bbfde27124d6bd1d77 to your computer and use it in GitHub Desktop.
Save abdheshkumar/b8ebca629bafe0bbfde27124d6bd1d77 to your computer and use it in GitHub Desktop.
How to implement typeclasses
trait Named[E] {
val name: String
}
case class EOL()
implicit val namedInt = new Named[Int] {
override val name: String = "Int"
}
implicit val namedChar = new Named[Char] {
override val name: String = "Char"
}
implicit val namedString = new Named[String] {
override val name: String = "String"
}
implicit val base = new Named[EOL] {
override val name: String = ""
}
implicit def inductionStep[Head, Tail](
implicit namedHead: Named[Head],
namedTail: Named[Tail]
): Named[(Head, Tail)] = new Named[(Head, Tail)] {
override val name: String = s"${namedHead.name}, ${namedTail.name}"
}
val result = implicitly[Named[Char]].name
implicitly[Named[(Int, String)]].name
implicitly[Named[(Int, (Char, (String, EOL)))]].name
//Result
/*
result: String = "Char"
res0: String = "Int, String"
res1: String = "Int, Char, String, "
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment