Learnerslesson
Learnerslesson

   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




KOTLIN - LAMBDA FUNCTION


A Lambda or Anonymous Function is a small one liner function that can just have only one expression.


Let us write the Function that adds two numbers and returns the result.


fun add(firstNumber: Int, secondNumber: Int): Int {
	var result = firstNumber + secondNumber
	return result
}

Now, let us write, exactly same Lambda or Anonymous Function for the above add Function.


var add = { firstNumber: Int, secondNumber: Int -> firstNumber + secondNumber }

And we are done.

Note : Just note that a Lambda Function can only have one expression.

Let us see the below example with to add two numbers using Lambda or Anonymous Function.


Example :



fun main() {

    var firstNum = 5
    var secondNum = 4

    var add = { firstNumber: Int, secondNumber: Int -> firstNumber + secondNumber }

    var value = add(firstNum, secondNum)
    println("The added result is "+value)
}


Output :



  The added result is 9

So, in the above code, we have the variables, firstNum and secondNum for addition of two numbers.


var firstNum = 5
var secondNum = 4
java_Collections


And in the next line, we call the Lambda or Anonymous Function.


var add = { firstNumber: Int, secondNumber: Int -> firstNumber + secondNumber }

The Lambda or Anonymous Function call is just like any other Function call. And the Lambda Function call is made.


var add = { firstNumber: Int, secondNumber: Int -> firstNumber + secondNumber }

And the Lambda or Anonymous Function is executed, adding two numbers and returning the added result.


And the added result is printed.


The added result is 9