2

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?

hammar
  • 138,522
  • 17
  • 304
  • 385
MohamedSanaulla
  • 6,112
  • 5
  • 28
  • 45

3 Answers3

5

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
2

The advantage is that sum(1,_,8) is less to type and read than x => sum(1,x,8).

That's all there is to it.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

sum(1,_,8) is less to type and read than x => sum(1,x,8)

However, neither is legal; you must provide the parameter type.

Jim Balter
  • 16,163
  • 3
  • 43
  • 66