in several different places in application, need take seq[salesrow]
, return map[string,salesrow]
, string name of country.
i need use in several places. example, take list of salesrows , global breakdown of sales country. in other places, want break down sales month , country (so map[month,seq[salesrow]]
becomes map[month,map[string,seq[salesrow]]]
) - in still other places, want break down day , country.
my question is: put (small) amount of logic takes seq[salesrow]
, returns map of countries rows? right now, i'm putting in companion object method, salesrow.bycountry(rows : seq[salesreport]
. optimal?
a crazier idea occurred me, create implicit conversion seq[salesrow]
enhancedsalesrowseq
, has bycountry
instance method. appeals me, because operation applicable sequence of salesrows.
is idea?
is adding logic companion object best choice, or there better options?
thanks.
in case not aware library comes groupby
function. given seq[salesrow]
give map[t, seq[salesrow]]
based on function salesrow
t
.
so if function easy can map. idea of enhanced seq in conjunction putting implicit in salesrow
companion:
case class salesrow(val month:int, val country:string, val person:string, val amount:float) class enhancedrow(rows: seq[salesrow]) { def bycountry: map[string, seq[salesrow]] = rows.groupby(_.country) def bymonth: map[int, seq[salesrow]] = rows.groupby(_.month) def bycountrybymonth: map[string, map[int, seq[salesrow]]] = bycountry.mapvalues(r => new enhancedrow(rows).bymonth) } object salesrow { implicit def toenhanced(rows: seq[salesrow]) = new enhancedrow(rows) } object test { def main(args:array[string] = null) { val seq: seq[salesrow] = // ... fill println(seq.bycountry) println(seq.bycountrybymonth) // same as: println(seq.bycountry.mapvalues(_.bymonth)) } }
Comments
Post a Comment