Suppose I have a function of 2 parameters that I need to apply partially, I need to define it as:
def f(a: Int)(b: Int) = { /* some code */ }
Actually you can partially apply any method you want. Simply call the method and leave out params:
scala> def foo(a: Int, b: Int) = a*b
foo: (a: Int, b: Int)Int
scala> val x = foo(1,_: Int)
x: Int => Int =
scala> def bar(x: Int, y: Int, z: Int) = x*y+z
bar: (x: Int, y: Int, z: Int)Int
scala> bar(2,_:Int,6)
res0: Int => Int =
The only difference is, that you have to tell the compiler the type of the missing argument, because otherwise it could not decide between overloaded methods.
Another way, if you have a real function and not a method would be to call curried
on the function:
scala> val f = {(x:Int, y:Int) => x*y}
f: (Int, Int) => Int =
scala> f.curried
res2: Int => (Int => Int) =
And you can also create a function from a method with the _
:
scala> bar _
res6: (Int, Int, Int) => Int =
and then call curried
on that:
scala> (bar _).curried
res5: Int => (Int => (Int => Int)) =