Skip to content

Instantly share code, notes, and snippets.

@Khalian
Last active March 4, 2020 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Khalian/a0f079e3a98a37fccdfe9624e8e8adc1 to your computer and use it in GitHub Desktop.
Save Khalian/a0f079e3a98a37fccdfe9624e8e8adc1 to your computer and use it in GitHub Desktop.
typeclass
// Inspiration : https://alvinalexander.com/scala/fp-book/type-classes-101-introduction
// Purpose : Adhoc polymorphsim
// Define some types
case class Dog(name: String, breed: String)
// Define the type class
trait Animal[A] {
def sound(a: A): Unit
}
// Define a callable interface object
object AnimalInstances {
def makeSound[A](a: A)(implicit animal: Animal[A]): Unit = {
animal.sound(a)
}
}
// Define a type class instance, these are defined adhoc where we want
implicit val dogVal = new Animal[Dog] {
def sound(dog: Dog): Unit = {
println(s"I'm a Dog, my name is ${dog.name} and my breed is ${dog.breed}")
}
}
// Use the type class in code.
val brendansdog = new Dog("Arnie", "Scottish Terrier")
AnimalInstances.makeSound(brendansdog)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment