Created
August 10, 2017 09:33
-
-
Save abdheshkumar/b8ebca629bafe0bbfde27124d6bd1d77 to your computer and use it in GitHub Desktop.
How to implement typeclasses
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 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