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)
leewz
  • 3,201
  • 1
  • 18
  • 38
  • What would you expect the result of `List('a','b','c').map(bah)` to be? – DCKing Jul 02 '14 at 08: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'))`. – leewz Jul 02 '14 at 08:10

1 Answers1

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.

cloud
  • 1,057
  • 7
  • 12
  • What makes this a method? Removing the second parameter removes the error: `def bah(c:Char) = 0`. – leewz Jul 02 '14 at 08:14
  • But then why does removing the second parameter allow the method to be passed? – leewz Jul 02 '14 at 08:39
  • @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) => ?`. – cloud Jul 02 '14 at 08:44
  • 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. – leewz Jul 02 '14 at 19:28
  • Would you mind if I edit the answer later with information I think would be helpful for understanding? – leewz Jul 02 '14 at 19:34