This file contains 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
// 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