Last active
March 4, 2020 08:12
-
-
Save Khalian/a0f079e3a98a37fccdfe9624e8e8adc1 to your computer and use it in GitHub Desktop.
typeclass
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
// 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