Last active
October 19, 2019 02:26
-
-
Save decapo01/bd127ca260db93b5ff312d9bf1baf20e to your computer and use it in GitHub Desktop.
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
final case class MyCaseClass(id: Int, name: String) | |
final case class MyOtherCaseClass(id: Int, name: String) | |
trait Show[-A]{ | |
def show(a: A): String | |
} | |
object Show { | |
def apply[A](a: A)(implicit sh: Show[A]) = implicitly[Show[A]].show(a) | |
implicit val intCanShow: Show[Int] = | |
new Show[Int]{ | |
def show(int: Int): String = s"int $int" | |
} | |
implicit val strCanShow: Show[String] = | |
new Show[String]{ | |
def show(str: String): String = s"a string $str" | |
} | |
implicit val myCaseClassCanShow: Show[MyCaseClass] = | |
new Show[MyCaseClass]{ | |
def show(myCaseClass: MyCaseClass): String = | |
Show(myCaseClass.id) + " " + Show(myCaseClass.name) | |
} | |
implicit def optCanShow[B : Show]: Show[Option[B]] = | |
new Show[Option[B]]{ | |
def show(opt: Option[B]): String = | |
opt match { | |
case Some(x) => "Some " + Show(x) | |
case None => "None" | |
} | |
} | |
} | |
println(Show(223)) | |
println(Show("hello")) | |
println(Show(Some(233))) | |
println(Show(Some("hello"))) | |
println(Show(Some(MyCaseClass(1,"eric")))) | |
//println(Show(Some(200.94203))) // <- will not compile | |
//println(Show(Some(MyOtherCaseClass(1,"eric")))) //<- will not compile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment