Search code examples
scalapartial-application

What are the applications/advantages of using partially applied functions in scala?


We have partially applied functions in Scala-

def sum(a:Int,b:Int,c:Int) = a+b+c

val partial1 = sum(1,_:Int,8)

I was wondering what are the advantages of using Partially applied functions. Or is it just a syntactical addition?


Solution

  • About partially applied function in general, the book "Programming in Scala, 2nd edition" mentions:

    Another way to think about this kind of expression, in which an underscore is used to represent an entire parameter list, is as a way to transform a def into a function value.
    For example, if you have a local function, such as sum(a: Int, b: Int, c: Int): Int, you can “wrap” it in a function value whose apply method has the same parameter list and result types.

    scala> def sum(a: Int, b: Int, c: Int) = a + b + c
    sum: (a: Int,b: Int,c: Int)Int
    scala> val a = sum _
    a: (Int, Int, Int) => Int = <function3>
    

    (Here, a(1, 2, 3) is a short form for:

    scala> a.apply(1, 2, 3)
    res12: Int = 6
    

    )

    Although you can’t assign a method or nested function to a variable, or pass it as an argument to another function, you can do these things if you wrap the method or nested function in a function value by placing an underscore after its name.