Skip to content

Instantly share code, notes, and snippets.

@harmeetsingh0013
Created April 11, 2018 17:41
Show Gist options
  • Save harmeetsingh0013/54d3f6d2060556f8bec32d9a28f73705 to your computer and use it in GitHub Desktop.
Save harmeetsingh0013/54d3f6d2060556f8bec32d9a28f73705 to your computer and use it in GitHub Desktop.
// 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