Skip to content

Instantly share code, notes, and snippets.

@knightpop
Created October 7, 2017 16:44
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 knightpop/f65305ed68a827bf3dba8951107d3b64 to your computer and use it in GitHub Desktop.
Save knightpop/f65305ed68a827bf3dba8951107d3b64 to your computer and use it in GitHub Desktop.
case class Hello(value: String)
trait Printer[T] {
def print(value: T): String
}
object Printer {
implicit val IntPrinter: Printer[Int] = new Printer[Int] {
override def print(value: Int): String = s"Type: Int - $value"
}
implicit val PersonPrinter: Printer[Hello] = new Printer[Hello] {
override def print(value: Hello): String = s"Type: Hello - $value"
}
}
def print[T](value: T)(implicit printer: Printer[T]): String = printer.print(value)
val int: Int = 1
val hello: Hello = Hello("ktz")
print(int) // Type: Int - 1
print(hello) // Type: Hello - Hello(ktz)
object InjectedObject {
implicit val injectedIntPrinter: Printer[Int] = new Printer[Int] {
override def print(value: Int): String = s"Injected - Type: Int - $value"
}
}
import InjectedObject.injectedIntPrinter
print(int) // Injected - Type: Int - 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment