Search code examples
scalafunctional-programmingdefault-parameters

Passing a function with default parameters


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)

Solution

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