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.
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)
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