I am trying to group by key and sum the values up in scala!
But when I perform the below operation, I get the return type as List[(String, Long)] instead of 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 tried
reconInput.groupBy(_.FeeDescription).mapValues(_.foldLeft(0L)(_+_.FeeAmount)).toList
I am getting the Expected data in the result but the type of List is different than what I expected
List(InputRecord("Visa Auth Fee", 70), InputRecord("Master Network Fee", 50))
But I get the return type as
List[(String, Long)]
instead of
List[InputRecord]
When I tried to cast the list to the expected one using the below command
val outputRecord = reconInput.groupBy(_.FeeDescription).mapValues(_.foldLeft(0L)(_+_.FeeAmount)).toList.asInstanceOf[ReconRecord]
i am getting class cast exception
Exception in thread "main" java.lang.ClassCastException: scala.collection.immutable.$colon$colon cannot be cast to
Sample$InputRecord
You're pretty close.
Scala cannot find the relation between the Pair of primitive types
(String, Int)and the case class ofInputRecorddefined by you.So you would need to explicitly map your output to the type that you want.