Skip to content

Instantly share code, notes, and snippets.

@aaabramov
Last active March 16, 2018 09:05
Show Gist options
  • Save aaabramov/0629a8e96292db75f898c80512e0d857 to your computer and use it in GitHub Desktop.
Save aaabramov/0629a8e96292db75f898c80512e0d857 to your computer and use it in GitHub Desktop.
Implicit parameter in traits
trait PrettyPrinted[A] extends (A => String)
object PrettyPrinted {
def apply[A](f: A => String): PrettyPrinted[A] = f(_)
}
trait Printable[A] {
implicit def printer: PrettyPrinted[A]
}
// implicit parameter name is important
case class Person(name: String, age: Int)
(implicit val printer: PrettyPrinted[Person])
extends Printable[Person]
object Person {
implicit val printer: PrettyPrinted[Person] =
PrettyPrinted { p =>
s"Person[name = ${p.name}, age = ${p.age}]"
}
}
// works also with regular classes
class Car(val name: String)
(implicit val printer: PrettyPrinted[Car])
extends Printable[Car]
object Car {
implicit val printer: PrettyPrinted[Car] =
PrettyPrinted { c =>
s"Car[name = ${c.name}]"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment