Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// add implementation for int type
implicit val addInt = new Addable[Int] {
override def add(a: Int, b: Int): Int = a + b
}
// add implementation for money type
implicit val addMoney = new Addable[Money] {
override def add(a: Money, b: Money): Money = {
Money(a.dollars + b.dollars + ((a.cents + b.cents) / 100),
(a.cents + b.cents) % 100)
}
}
// add implementation for add two maps
// [V: Addable] is shothand of (implicit addable: Addable[A])
implicit def addMap[K, V: Addable] = new Addable[Map[K, V]] {
override def add(a: Map[K, V], b: Map[K, V]): Map[K, V] = {
a.foldLeft(b) {
case (acc, (x, y)) =>
acc + (x -> acc.get(x).map(implicitly[Addable[V]].add(_, y)).getOrElse(y))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment