When do I have to treat my methods as partially applied functions in Scala?

Senthess picture Senthess · Jul 11, 2011 · Viewed 11.4k times · Source

I noticed that when I'm working with functions that expect other functions as parameters, I can sometimes do this:

someFunction(firstParam,anotherFunction)

But other times, the compiler is giving me an error, telling me that I should write a function like this, in order for it to treat it as a partially applied function:

someFunction(firstParam,anotherFunction _)

For example, if I have this:

object Whatever {
    def meth1(params:Array[Int]) = ...
    def meth2(params:Array[Int]) = ...
}

import Whatever._
val callbacks = Array(meth1 _,meth2 _)

Why can't I have the code like the following:

val callbacks = Array(meth1,meth2)

Under what circumstances will the compiler tell me to add _?

Answer

Jean-Philippe Pellet picture Jean-Philippe Pellet · Jul 11, 2011

The rule is actually simple: you have to write the _ whenever the compiler is not explicitly expecting a Function object.

Example in the REPL:

scala> def f(i: Int) = i    
f: (i: Int)Int

scala> val g = f
<console>:6: error: missing arguments for method f in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       val g = f
               ^

scala> val g: Int => Int = f  
g: (Int) => Int = <function1>