Created
March 12, 2017 19:12
-
-
Save anonymous/7df2b79f1df437aab1a374e59996c236 to your computer and use it in GitHub Desktop.
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
//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