Scala – First Class Functions

  • date 20th May, 2021 |
  • by Prwatech |
  • 0 Comments

In functional programming, functions are assigned to variables, passed to other functions as parameters, and returned as values from other functions. Such functions are called as First Class Functions.

Use case 1:

Assign function as Variable
scala>(i:Int) => {i*2}
scala>val doubler = (i:Int) => {i*2}
scala>doubler(5)

Use case 2:

Pass function as Parameter
scala>def operation(functionparam:(Int, Int) => Int){
       println(functionparam(10,5))
      }
scala> val sum = (x:Int, y:Int)=> x+y
scala>operation(sum);
scala>val diff = (x:Int, y:Int)=> x-y
scala>operation(diff);

Use case 3:

Return a Function
object prwatech {
   def main(args: Array[String]) {

    val doubleValue = doubler();
    print("Double of 2 = " + doubleValue(2));
  }

  def doubler() = (num: Int) => num * 2;
}
Output
Double of 2 = 4

Quick Support

image image