Reputation: 61
I'm trying to add key, value pairs in a Map
using reduceLeft()
but am getting a error. If I add the key value pair using foldleft()
I get the right answer. What does this Error mean in reduceLeft
and what is the correct code?
Code:
object Dcoder extends App
{
var i = Map(1->2, 3->4, 5->6)
var o = i.reduceLeft((a,b) => a._1 + b._1)
println(o)
}
Error:
source_file.scala:9: error: type mismatch;
found : Int
required: (Int, Int)
var o=i.reduceLeft((a,b)=>a._1+b._1)
^
one error found
Upvotes: 1
Views: 200
Reputation: 51271
You can fold
from one type to another but reduce
is more restrictive. You can't reduce a collection of pairs, type (Int,Int)
, to a single type Int
.
This works by reducing a collection of pairs to a singe pair and then stripping away the 2nd element.
Map(1->2, 3->4, 5->6).reduceLeft(_._1 + _._1 -> 0)._1 //res0: Int = 9
Upvotes: 2