Skip to content

Instantly share code, notes, and snippets.

@jiamingd
Last active July 24, 2017 05:36
Show Gist options
  • Save jiamingd/031015673364307e9a06a90cf937ffe6 to your computer and use it in GitHub Desktop.
Save jiamingd/031015673364307e9a06a90cf937ffe6 to your computer and use it in GitHub Desktop.
Drill on how type class with implicit bring in polymorphism
trait Show[A] {
def doShow(input : A) : String
}
// Value class apporach need more tune up
// Value class: Goal is to avoid a runtime overhead
//implicit class LetShowable[A](val a: A) extends AnyVal{
// def letShow(implicit sh: Show[A]) = sh.doShow(a)
//}
object Show {
def apply[A]()(implicit sa: Show[A]) : Show[A] = sa
implicit class LetShowable[A: Show](val a: A) {
def letShow = implicitly[Show[A]].doShow(a)
}
// using apply will avoid using implicitly
def showUseApply[A: Show](a: A) : Unit = {
println( Show.apply[A].doShow(a) )
println(Show[A].doShow(a))
}
def showBetter[A: Show](a: A ) : Unit = {
val impAInstance = implicitly[Show[A]]
println(impAInstance.doShow(a))
}
def show[A](a: A)(implicit sa : Show[A]) : Unit = {
println(sa.doShow(a))
}
implicit val intShow = new Show[Int] {
override def doShow(input : Int): String = input.toString
}
}
import Show._
show(12)
showBetter(23)
showUseApply(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment