Created
November 21, 2018 17:23
-
-
Save kolemannix/c00844922b363229b7b9db6e0d56427e to your computer and use it in GitHub Desktop.
Code from: "An introduction to typeclasses 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
#!/usr/bin/env amm | |
// Snippet 1 | |
@scala.annotation.implicitNotFound("No Showable[A] in scope for A = ${A}. Try importing or defining one.") | |
trait Showable[A] { | |
def show(a: A): String | |
} | |
// Snippet 2 | |
object Showable { | |
def make[A](showFn: A => String): Showable[A] = new Showable[A] { override def show(a: A): String = showFn(a) } | |
} | |
final case class UserName(first: String, last: String) | |
implicit val defaultUserNameShowable = Showable.make[UserName](userName => s"${userName.first} ${userName.last}") | |
val janeName = UserName("Jane", "Doe") | |
// Snippet 3 | |
defaultUserNameShowable.show(janeName) // "Jane Doe" | |
// Snippet 4 | |
implicit class ShowSyntax[A](val a: A) extends AnyVal { | |
def show(implicit showable: Showable[A]): String = showable.show(a) | |
} | |
janeName.show | |
// Snippet 5 | |
implicit val secretUserNameShowable = Showable.make[UserName](_ => "<secret person>") | |
//janeName.show | |
// Snippet 6 | |
//java.util.UUID.randomUUID().show | |
// > typeclasses.sc:32: No Showable[A] in scope for A = java.util.UUID. Try importing or defining one. | |
// Snippet 7 | |
trait SafeSerializable[A] { | |
def serialize(a: A): Array[Byte] | |
def deserialize(bytes: Array[Byte]): A | |
} | |
trait Functor[F[_]] { | |
def map[A, B](a: F[A], f: A => B): F[B] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment