Skip to content

Instantly share code, notes, and snippets.

@gigiigig
Last active November 8, 2015 10:22
Show Gist options
  • Save gigiigig/fd64153518bf5d12c1fa to your computer and use it in GitHub Desktop.
Save gigiigig/fd64153518bf5d12c1fa to your computer and use it in GitHub Desktop.
object console extends App {
trait Printer[T] {
def print(t: T): String
}
object Printer {
implicit val intPrinter: Printer[Int] = new Printer[Int] {
def print(i: Int) = s"$i: Int"
}
implicit def optionPrinter[V](implicit pv: Printer[V]): Printer[Option[V]] =
new Printer[Option[V]] {
def print(ov: Option[V]) = ov match {
case None => "None"
case Some(v) => s"Option[${pv.print(v)}]"
}
}
implicit def listPrinter[V](implicit pv: Printer[V]): Printer[List[V]] =
new Printer[List[V]] {
def print(ov: List[V]) = ov match {
case Nil => "Nil"
case l: List[V] => s"List[${l.map(pv.print).mkString(", ")}]"
}
}
}
def print[T](t: T)(implicit p: Printer[T]) = p.print(t)
val res = print(Option(List(1, 3, 6)))
println(s"res: ${res}")
// res: Option[List[1: Int, 3: Int, 6: Int]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment