Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map error when applying on list of tuples in scala

Tags:

lambda

scala

If applying map method to a list of tuple in Scala, it complains error as below:

scala> val s = List((1,2), (3,4))
s: List[(Int, Int)] = List((1,2), (3,4))

scala> s.map((a,b) => a+b)
<console>:13: error: missing parameter type
Note: The expected type requires a one-argument function accepting a 2-Tuple.
    Consider a pattern matching anonymous function, `{ case (a, b) =>  ... }`
    s.map((a,b) => a+b)
            ^
<console>:13: error: missing parameter type
    s.map((a,b) => a+b)

But if I apply similar map method to list of Int, it works fine:

scala> val t = List(1,2,3)
t: List[Int] = List(1, 2, 3)

scala> t.map(a => a+1)
res14: List[Int] = List(2, 3, 4)

Anyone knows why it is? Thanks.

like image 887
KAs Avatar asked Nov 15 '16 18:11

KAs


People also ask

How do I convert a list to map in Scala?

In Scala, you can convert a list to a map in Scala using the toMap method. A map contains a set of values i.e. key-> value but a list contains single values. So, while converting a list to map we have two ways, Add index to list.

What is the difference between list and tuple in Scala?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.

Is tuple mutable in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable.


1 Answers

Scala dosen't deconstruct tuples automatically. You'll need to either use curly brackets:

val s = List((1,2), (3,4))
val result = s.map { case (a, b) => a + b }

Or use a single parameter of type tuple:

val s = List((1,2), (3,4))
val result = s.map(x => x._1 + x._2)

Dotty (the future Scala compiler) will bring automatic deconstruction of tuples.

like image 115
Yuval Itzchakov Avatar answered Sep 28 '22 08:09

Yuval Itzchakov