1

Attempting to compile the function below in scala 2.11.0

def dafuq(canvas: Array[Array[Boolean]]): Array[Array[Boolean]] = {
        for (r <- canvas.reverse) yield r.zipWithIndex.map((c: Boolean, i: Int) => c) 
}

yields

Solution.scala:6: error: type mismatch;
   found   : (Boolean, Int) => Boolean
   required: ((Boolean, Int)) => ?
        for (r <- canvas.reverse) yield r.zipWithIndex.map((c: Boolean, i: Int) => c) 
                                                                                ^

The function is bogus but it illustrates a problem that I have encountered. I'm quite new to Scala so this could be a rookies mistake but I cannot find any solution or explanation to this problem. Do you know what causes the above behaviour?

Also is return type hinting possible for lambda expressions?

1 Answer 1

3

I ran into this compile error many times too, but it's not a type inference issue. You supplied an anonymous function with 2 arguments, but the compiler expected a function with a single tuple argument. 2 solutions:

def dafuq(canvas: Array[Array[Boolean]]): Array[Array[Boolean]] = {
        for (r <- canvas.reverse) yield r.zipWithIndex.map(ci => ci._1)
}

or

def dafuq(canvas: Array[Array[Boolean]]): Array[Array[Boolean]] = {
        for (r <- canvas.reverse) yield r.zipWithIndex.map { case (c, i) => c }
}

In the first solution ci is inferred to a pair (Boolean, Int). In the second solution we use a pattern match expression.

Also is return type hinting possible for lambda expressions?

I don't know, but you can add type annotations on any expression. For example: case (c, i) => c: Boolean.

Sign up to request clarification or add additional context in comments.

2 Comments

The second snippet uses a pattern match expression to define a function. It isn't a PartialFunction; it's a Function1 (and it isn't partial, as it's defined over its entire domain). SLS section 8.5 specifies that a pattern match expression desugars to either FunctionN or PartialFunction depending on the context. In this case, since map expects a Function1, that's what it is.
I only know this because someone else has corrected me on stackoverflow before, so... keep passing it along :)

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.