I want to call map()
on a list of pairs, but I get a type mismatch error.
For example, suppose I want to map a List of pairs of Int to a list of their sums:
scala> val ll=List((1,2),(3,4),(5,6)) ll: List[(Int, Int)] = List((1,2), (3,4), (5,6)) scala> ll.map((x:Int,y:Int)=>x+y) <console>:9: error: type mismatch; found : (Int, Int) => Int required: ((Int, Int)) => ? ll.map((x:Int,y:Int)=>x+y) ^
By the way, when trying to run foreach() I get a very similar error:
scala> ll.foreach((x:Int,y:Int)=>println(x,y)) <console>:9: error: type mismatch; found : (Int, Int) => Unit required: ((Int, Int)) => ? ll.foreach((x:Int,y:Int)=>println(x,y)) ^
What does the ?
sign stand for? What am I missing here?
To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.
Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.
The concatenation of Scala map is obtained by utilizing ++ operator. Return Type: It returns a single map by concatenating two maps but it separates the identical keys. As we can see in above example, we joined two maps by using ++ operator.
You can use pattern matching to get the elements of the pair.
ll.map{ case (x:Int,y:Int) => x + y }
You don't even need to specify the types:
ll.map{ case (x, y) => x + y }
The same works with foreach
of course.
The error message tells you that the compiler expected to find a function of one parameter (a pair of ints) to any type (the question mark) and instead found a function of two parameters, both ints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With