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.
Let us see the below example with to add two numbers using Lambda or Anonymous Function.
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) }
So, in the above code, we have the variables, firstNum and secondNum for addition of two numbers.
var firstNum = 5 var secondNum = 4
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.
We have explained the details of Lambda or Anonymous Function.
And the added result is printed.
The added result is 9