Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call .map() on a list of pairs in Scala

Tags:

scala

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?

like image 675
akiva Avatar asked Oct 16 '12 11:10

akiva


People also ask

How do I create a map from a list in scala?

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.

How do you access map elements in scala?

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.

How do you add two maps in scala?

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.


1 Answers

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.

like image 68
Kim Stebel Avatar answered Sep 18 '22 23:09

Kim Stebel