5

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.

3
  • We need to see some of the code. The part of the code that was printed with the error message is not enough. In particular, what's the type signature of doMyStuff, and what kind of variable are you trying to write the result to? Commented Jan 11, 2012 at 0:10
  • Are you sure the error message doesn't say required: ((Int, List[InputEntry])) => ? Commented Jan 11, 2012 at 0:23
  • I guess I should have made it more specific that entries is a Map. Thanks anyway Commented Jan 11, 2012 at 7:07

1 Answer 1

14

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Whoops I'm wrong: he reported the error message wrong. Once you account for this, I should actually give a +1 instead.
The corresponding bug is marked fixed, so it should not be there in the next version : issues.scala-lang.org/browse/SI-5067
@KenBloom: please read my comment, I actually copy-pasted the error message. Thanks everybody, anyway :)
+1: Like the use of case to destructure args. Better than val (k: Int, ies: Array[InputEntry]) = tuple

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.