0

I have multiple case classes that represent some sort of dimensions, and some sort of field level statistics that can be aggregated agnostic from all the other fields. This forms a semigroup by defining combine

case class Precipitation(date: String, rainInches: Double, snowInches: Double)

def combine(p1: Precipitation, p2:Precipitation): Precipitation = {
   p1.copy(rainInches=p1.rainInches + p2.rainInches,
           snowInches=p1.snowInches + p2.snowInches)
}

case class GroceryList(
  groceryListId: String, 
  groceryStoreName: String, 
  eggs: Int, 
  peaches: Int, 
  flourPounds: Double)


def combine(g1: GroceryList, g2: GroceryList): GroceryList = {
   g1.copy(eggs = g1.eggs + g2.eggs,
           peaches = g1.peaches + g2.peaches, 
           flourPounds = g1.flourPounds + g2.flourPounds)
}

For a pure aggregation with no state like this, it would be nice to define a more generic semigroup trait that both Precipitation and GroceryList extend, that can deal with arbitrary names and numbers of fields.

Michael K
  • 2,196
  • 6
  • 34
  • 52

0 Answers0