What will be the result of combining Semigroup of type Map with the same keys?
import cats.implicits._
import cats.kernel.Semigroup

val aMap = Map("foo" → Map("bar" → 5))
val anotherMap = Map("foo" → Map("bar" → 6))
val combinedMap = Semigroup[Map[String, Map[String, Int]]].combine(aMap, anotherMap)

combinedMap.get("foo")
Explanation
When combining Maps, the value from one Map is added to the other if the key doesn’t exist or value with the associated key is updated as a result of applying combine for values. Combining Ints is implemented as sum. In the current example, the full combination can be traced in the following way:

  Semigroup[Map[String, Map[String, Int]]].combine(Map("foo" → Map("bar" → 5)), Map("foo" → Map("bar" → 6))) ==
  Map("foo" -> Semigroup[Map[String, Int]].combine(Map("bar" -> 5), Map("bar" -> 6))) ==
  Map("foo" -> Map("bar" -> Semigroup[Int].combine(5, 6))) ==
  Map("foo" -> Map("bar" -> (5 + 6))) ==
  Map("foo" -> Map("bar" -> 11))


Source: Scala Exercises: cats semigroup

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes