0

In Scala (v2.8.0, on SimplyScala.com), if I define a 2-ary function with a default parameter, why can't I pass it as a 1-ary function?

This

def bah(c:Char, i:Int = 0) = i
List('a','b','c').map(bah)

gives this

error: type mismatch;
 found   : (Char, Int) => Int
 required: (Char) => ?
       List('a','b','c').map(bah)
2
  • What would you expect the result of List('a','b','c').map(bah) to be? Commented Jul 2, 2014 at 8:04
  • I'd expect List(0,0,0). More generally, I'd expect it to be equivalent to List(bah('a'), bah('b'), bah('c')). Commented Jul 2, 2014 at 8:10

1 Answer 1

2

What you defined is a method, not a function.

What scala do is translate List('a','b','c').map(bah) to List('a','b','c').map((c: Char, i: Int) => bah(c, i)), because map need a function, you can't pass a method to it.

Finally, scala found type mismatch and warn you.

A workaround:

List('a','b','c').map(c => bah(c))

Edit:

A further explanation, we can only pass functions as parameters not method(because function is object), and there is no way to cast a method to a function, you can only build a function calling that method. But sometimes scala can build that function for you from a method which makes you mistakenly think method can be passed as parameter.

Anyway, building function is easy in scala. And with type inference, you can omit the type of input parameter when pass it to a method like List('a','b','c').map(c => bah(c)), you build a function c => bah(c) and you don't need to point out c is Char.

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

5 Comments

What makes this a method? Removing the second parameter removes the error: def bah(c:Char) = 0.
But then why does removing the second parameter allow the method to be passed?
@leewangzhong like I said in the answer, scala will translate it to a function. If your method only have one parameter, then the translated function also has only one parameter which match the type (Char) => ?.
Is there a way to "cast" it to a function, or must I define the function manually? I think I see the problem, but I think your answer isn't really informative enough for a general Scala newbie.
Would you mind if I edit the answer later with information I think would be helpful for understanding?

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.