Scala:如何在Scala中按键分组和求和,并以期望的返回类型返回列表



我正在尝试按键分组并在scala中求和!

但是当我执行下面的操作时,我得到的返回类型是List[(String, Long)]而不是List[InputRecord]

case class InputRecord(FeeDescription: String, FeeAmount: Long)
val reconInput : List[InputRecord] = List(InputRecord("Visa Auth Fee", 30), InputRecord("Visa Auth Fee", 40),
InputRecord("Master Network Fee", 50))

Command i trying

reconInput.groupBy(_.FeeDescription).mapValues(_.foldLeft(0L)(_+_.FeeAmount)).toList

我在结果中得到预期的数据,但列表的类型与我预期的不同

List(InputRecord("Visa Auth Fee", 70), InputRecord("Master Network Fee", 50))
但是我得到的返回类型是
List[(String, Long)] 

不是

List[InputRecord]

当我试图使用下面的命令

将列表转换为期望的列表时
val outputRecord = reconInput.groupBy(_.FeeDescription).mapValues(_.foldLeft(0L)(_+_.FeeAmount)).toList.asInstanceOf[ReconRecord]

我得到类强制转换异常

Exception in thread "main" java.lang.ClassCastException: scala.collection.immutable.$colon$colon cannot be cast to 
Sample$InputRecord

你很接近了。

Scala找不到Pair的基本类型(String, Int)和你定义的InputRecord的case类之间的关系。


case class InputRecord(FeeDescription: String, FeeAmount: Long)
val reconInput : List[InputRecord] = List(
InputRecord("Visa Auth Fee", 30),
InputRecord("Visa Auth Fee", 40),
InputRecord("Master Network Fee", 50)
)
val output1 = reconInput.groupBy(_.FeeDescription).mapValues(_.foldLeft(0L)(_+_.FeeAmount)).toList
/*
val output1: List[(String, Long)] = List((Master Network Fee,50), (Visa Auth Fee,70))
*/

所以你需要显式地将你的输出映射到你想要的类型。

val output2 = output1.map(pair => InputRecord(pair._1, pair._2))
/*
val output2: List[InputRecord] = List(InputRecord(Master Network Fee,50), InputRecord(Visa Auth Fee,70))
*/