问题描述
在我的应用程序中的几个不同位置,我需要使用Seq[SalesRow]
并返回Map[String,SalesRow]
,其中字符串是国家/地区的名称.
In several different places in my application, I need to take a Seq[SalesRow]
and return a Map[String,SalesRow]
, where the string is the name of a country.
我需要在多个地方使用它.例如,我列出了所有SalesRows的列表,并按国家/地区获得了销售的全球细分.但是在其他地方,我想按月细分销售,然后按国家细分(所以Map[Month,Seq[SalesRow]]
变成Map[Month,Map[String,Seq[SalesRow]]]
)-在其他地方,我想按天细分,然后按国家细分.
I need to use this in several places. For example, I take a list of all SalesRows and get a global breakdown of sales by country. But in other places, I want to break down my sales by month and then by country (so Map[Month,Seq[SalesRow]]
becomes Map[Month,Map[String,Seq[SalesRow]]]
) - in still other places, I want to break down by day and then by country.
我的问题是:我应该把(c)>(返回)行的国家/地区地图的(少量)逻辑放在哪里?现在,我将其放在伴随对象方法SalesRow.byCountry(rows : Seq[SalesReport]
中.那是最佳选择吗?
My question is: where do I put the (small) amount of logic that takes a Seq[SalesRow]
and returns a map of countries to rows? Right now, I'm putting it in a companion object method, SalesRow.byCountry(rows : Seq[SalesReport]
. Is that optimal?
我想到了一个有点疯狂的想法,那就是创建一个从Seq[SalesRow]
到EnhancedSalesRowSeq
的隐式转换,该转换具有一个byCountry
实例方法.这对我很有吸引力,因为该操作适用于任何序列的SalesRows.
A slightly crazier idea occurred to me, which is to create an implicit conversion from Seq[SalesRow]
to EnhancedSalesRowSeq
, which has a byCountry
instance method. This appeals to me, because the operation is applicable to any sequence of SalesRows.
这是个好主意吗?
是将逻辑添加到伴随对象中是我的最佳选择,还是有更好的选择?
Is adding the logic to the companion object my best choice, or are there better options?
谢谢.
推荐答案
如果您不知道该库随附了 groupBy
函数.基本上给定Seq[SalesRow]
,它将根据从SalesRow
到T
的函数为您提供Map[T, Seq[SalesRow]]
.
In case you are not aware the library comes with a groupBy
function. Basically given a Seq[SalesRow]
it will give you a Map[T, Seq[SalesRow]]
based on a function from SalesRow
to T
.
因此,如果您的功能很简单,则可以轻松获取地图.我很喜欢您关于增强seq的想法,并将隐式放在SalesRow
随播广告中:
So if your function is easy you can easily get a map. I do like your idea of the enhanced seq in conjunction with putting the implicit in the 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 this
println(seq.byCountry)
println(seq.byCountryByMonth)
// same as:
println(seq.byCountry.mapValues(_.byMonth))
}
}
这篇关于如何处理特定种类的馆藏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!