Partially Applied Function : Example

The arguments for a function can also be Applied at compile time ; hence the term Partially Applied Function
scala> // Function to multiply 3 arguments

scala> def multiply(x:Int, y:Int, z:Int) : Int = {
 | val result = x * y * z
 | result
 | }
multiply: (x: Int, y: Int, z: Int)Int

scala> // Pass all the arguments at run time

scala> val passallarguments = multiply _
passallarguments: (Int, Int, Int) => Int = <function3>

scala> passallarguments(1, 2, 3)
res15: Int = 6

scala> // Pass only 2 arguments at run time

scala> val passonly2arguments = multiply(_:Int, _:Int, 2)
passonly2arguments: (Int, Int) => Int = <function2>

scala> passonly2arguments(3, 4)
res16: Int = 24

scala> // This does not work

scala> val thisdonotwork = multiply
<console>:55: error: missing arguments for method multiply;
follow this method with `_' if you want to treat it as a partially applied function
 val thisdonotwork = multiply
 ^
c111 > a50 > a11

No comments:

Post a Comment