Partial application

In Scala, the underscore(_) means different things in different contexts. The underscore can be used to partially apply a function. It means a value will be supplied later. This feature is useful for function composition and allows you to reuse functions. Let's see some code.

Partial function in Scala REPL

Following is an example using Partial function in Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>def sum(a:Int,b:Int) = a+b

sum: (a: Int, b: Int)Int


scala>val add6 = sum(6,_:Int) add6: Int => Int = scala>




In the preceding code, first, we define a function called sum, which takes two Int parameters and calculates a sum of these two parameters. Later, we define a function and hold it as a variable called add6. For the add6 function definition, we just call the sum function passing 6 and _. Scala will get the parameter passed through add6, and pass it through the sum function.

< Prev   CONTENTS   Source   Next >