Last active
March 23, 2018 09:32
-
-
Save wibisono/28d8808159e0c7103042d7c5c668edf7 to your computer and use it in GitHub Desktop.
Example speaking type class, rewrite from Simplified FP chapter Typeclass 101
This file contains hidden or 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
| // Base type | |
| sealed trait Animal | |
| case class Dog(name:String) extends Animal | |
| case class Cat(name:String) extends Animal | |
| // Type class | |
| trait Speaking [A] { | |
| def speak(creature : A) : String | |
| } | |
| // Type class instance | |
| implicit val speakingDog = new Speaking[Dog] { | |
| def speak(dog : Dog) = s"I am speaking dog called ${dog.name}" | |
| } | |
| // Instance | |
| val lassie = Dog("Lassie") | |
| // Direct use of implicit instance using implicitly | |
| implicitly[Speaking[Dog]].speak(lassie) | |
| // Interface Object | |
| object Speaking { | |
| def speak[A : Speaking](creature : A) = implicitly[Speaking[A]].speak(creature) | |
| } | |
| // Scala with Cats call this Interface Object, FP Simplified call this explicit way | |
| Speaking.speak(lassie) | |
| object SpeakingSyntax { | |
| implicit class SpeakingCreature[A](creature : A) { | |
| def speak(implicit speakingA : Speaking[A]) : String = speakingA.speak(creature) | |
| } | |
| } | |
| // Interface syntax version | |
| import SpeakingSyntax._ | |
| lassie.speak |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment