Kotlin-LambdaExpression

MaKB
2 min readJun 23, 2018

--

Lambda Expressions are the functions without name given as constant. generally Lambda Expressions are written as method parameter.

Syntax of Lambda Expressions is as follow

(arg1,arg2) -> returnType = { arg1 : DataType, arg2 : DataType -> Logic }

Example 1 :

Lambda expression to perform sum of 2 numbers, we can pass lambda expression as variable to a method or we can directly pass expression as a method parameter.

Use_1 :
In this example we are passing 2 numbers and lambda expressions variable which performs addtion of given numbers.

var lambda: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
addTwoNumbers(3, 7, lambda)

Use_2 :
In this example we are passing 2 numbers and lambda expression which performs addtion of given numbers

addTwoNumbers(3, 7, { x: Int, y: Int -> x + y })

Fun_def:
This is the function which accept lambda as method parameter and perform action which is specified in lambda expression.

fun addTwoNumbers(no1: Int, no2: Int, myLambda: (Int, Int) -> Int) {
var result = myLambda(no1, no2)
println(“ — Sum is — — “ + result)
}

Example 2:

Here is an example of lambda expression to find largest string amoung 2 strings

var LargeStringLambda: (String, String) -> Boolean = { a: String, b: String -> a.length > b.length }
println(“ — is manoj string is large — — “ + LargeStringLambda(“manoj”, “manojbhadane”))

Example 3:

Here is an example of lambda expression to find largest number amoung 2 numbers.

var LargeNumberLambda: (Int, Int) -> Int = { a: Int, b: Int -> if (a > b) a else b }
println(“ — large number is among 3,7 is — — “ + LargeNumberLambda(3, 7))

If this post was helpful, please click the clap 👏 button below a few times to show your support!

--

--

MaKB
MaKB

Written by MaKB

Experienced software engineer with demonstrated history of working in telecommunications industry along with many other sectors like education, e-commerce etc.

No responses yet