Skip to content

Instantly share code, notes, and snippets.

Created March 12, 2017 19:12
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 anonymous/7df2b79f1df437aab1a374e59996c236 to your computer and use it in GitHub Desktop.
Save anonymous/7df2b79f1df437aab1a374e59996c236 to your computer and use it in GitHub Desktop.
//type-class
trait Described[A] {
def description(a: A): String
}
implicit object IntDesc extends Described[Int] {
override def description(i: Int) = s"Int $i"
}
implicit object StrDesc extends Described[String] {
override def description(s: String) = s"String $s"
}
implicit def listDesc[T : Described]: Described[List[T]] =
new Described[List[T]] {
override def description(xs: List[T]) = {
val describer = implicitly[Described[T]]
val elemsDescription = (xs map describer.description).mkString(", ")
s"List [$elemsDescription]"
}
}
def describe[T : Described](entity: T) = implicitly[Described[T]].description(entity)
//tests
describe(1)
describe("a")
describe(List(1, 2, 3))
describe(List(List("a", "b"), List("c")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment