Skip to content

Instantly share code, notes, and snippets.

@wibisono
Last active March 23, 2018 09:32
Show Gist options
  • Select an option

  • Save wibisono/28d8808159e0c7103042d7c5c668edf7 to your computer and use it in GitHub Desktop.

Select an option

Save wibisono/28d8808159e0c7103042d7c5c668edf7 to your computer and use it in GitHub Desktop.
Example speaking type class, rewrite from Simplified FP chapter Typeclass 101
// 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