Last active
March 16, 2018 09:05
-
-
Save aaabramov/0629a8e96292db75f898c80512e0d857 to your computer and use it in GitHub Desktop.
Implicit parameter in traits
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 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