Created
March 4, 2019 12:54
-
-
Save erichonorez/cea669523d3e74d9e68e5752c4025a5d to your computer and use it in GitHub Desktop.
Type classes in scala
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 Show[A] { | |
def show(a: A): String | |
} | |
object Show { | |
// def apply[A](implicit sh: Show[A]): Show[A] = sh | |
def apply[A: Show]: Show[A] = implicitly[Show[A]] | |
object ops { | |
//def show[A](a: A)(implicit sh: Show[A]) = sh.show(a) | |
//def show[A: Show](a: A) = implicitly[Show[A]].show(a) | |
def show[A: Show](a: A) = Show[A].show(a) | |
/* | |
implicit class ShowOps[A: Show](a: A) { | |
def show = Show[A].show(a) | |
}*/ | |
implicit class ShowOps[A](val a: A) extends AnyVal { | |
def show(implicit sh: Show[A]) = sh.show(a) | |
} | |
} | |
/* | |
implicit val intCanShow: Show[Int] = new Show[Int] { | |
override def show(a: Int): String = s"int $a" | |
} | |
implicit val stringCanShow: Show[String] = new Show[String] { | |
override def show(a: String): String = s"string $a" | |
} | |
*/ | |
implicit val intCanShow: Show[Int] = a => s"int $a" | |
implicit val stringCanShow: Show[String] = a => s"string $a" | |
} | |
import Show._ | |
import Show.ops._ | |
println(intCanShow.show(20)) | |
println(show(20)) | |
println(20.show) | |
println("30".show) | |
case class Event(val msg: String) | |
implicit def eventCanShow: Show[Event] = event => s"event ${event.msg}" | |
println(Event("occured").show) | |
println(show(Event("occured"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment