Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala mismatch while mapping Map

I'm taking my first interesting steps (non-hello-world level) with Scala (2.9.1) and I'm stuck trying to understand a very uninformative error message. It goes much like this:

error: type mismatch;
found   : (Int, Array[InputEntry]) => (Int, Double)
required: (Int, Array[InputEntry]) => ?
entries.groupBy(grouper).map((k: Int, ies: Array[InputEntry]) => (k, doMyStuff(ies)))

As you can guess process in this snippet is supposed to be where some processing goes on, and it's actually a well defined function with signature Array[InputEntry] => Double.

Grouper's signature, instead, is Array[InputEntry] => Int.

I've tried to extract a function and replace the lambda but it was useless, and I'm stuck trying to understand the question mark in the error...

Any ideas?

Edit: I should clarify that InputEntry is a class I've defined, but for the sake of this example it seems to me like it's hardly relevant.

like image 540
em70 Avatar asked Jan 10 '12 23:01

em70


1 Answers

This looks like the problem:

.map((k: Int, ies: Array[InputEntry]) => (k, doMyStuff(ies)))

You need to use a case statement to unapply the params and assign them to local variables. You also need to use {} instead of () because it is an anonymous function now.

entries.groupBy(grouper).map{case (k, ies) => (k, doMyStuff(ies))}

Here's a more simple example.

scala> val x = List(("a",1),("b",2))
x: List[(java.lang.String, Int)] = List((a,1), (b,2))
scala> x.map{ case (str, num) => num }
res5: List[Int] = List(1, 2)

If you don't want to use a case statement, you have to keep the tuple as a single variable.

scala> x.map(tuple => tuple._2)
res6: List[Int] = List(1, 2)
like image 193
tommy chheng Avatar answered Sep 20 '22 00:09

tommy chheng