Lambda Kotlin

Higher order functions

fun main(args: Array<String>) { val program = Program() program.addTwoNumbers(2, 7) // Simple way... for better understanding program.addTwoNumbers(2, 7, object : MyInterface { // Using Interface / OOPs way override fun execute(sum: Int) { println(sum) // Body } }) val test: String = "Hello" val myLambda: (Int) -> Unit = { s: Int -> println(s)} // Lambda Expression [ Function ] program.addTwoNumbers(2, 7, myLambda) } class Program { fun addTwoNumbers(a: Int, b: Int, action: (Int) -> Unit) { // High Level Function with Lambda as Parameter val sum = a + b action(sum) // println(sum) // println(sum) // Body } fun addTwoNumbers(a: Int, b: Int, action: MyInterface) { // Using Interface / Object Oriented Way val sum = a + b action.execute(sum) } fun addTwoNumbers(a: Int, b: Int) { // Simple way.. Just for Better Understanding val sum = a + b println(sum) } } interface MyInterface { fun execute(sum: Int) }

High level functions

- Can accept Functions as parameters

- Can return a Function

- Or can do both

----------

Lambdas

It is just a Function with no name

Lambda

fun main(args: Array<String>) { val program = MyProgram() // val myLambda: (Int, Int) -> Int = { x, y -> x + y} // Lambda Expression [ Function ] // OR, // program.addTwoNumbers(2, 7, { x, y -> x + y }) // OR, program.addTwoNumbers(2, 7) {x, y -> x + y} } class MyProgram { fun addTwoNumbers(a: Int, b: Int, action: (Int, Int) -> Int) { // High Level Function with Lambda as Parameter val result = action(a, b) println(result) } }

Diferent ways to declare a lamda funcion in high level function

Closures

fun main(args: Array<String>) { val program = TheProgram() var result = 0 program.addTwoNumbers(2, 7) {x, y -> result = x + y} println(result) } class TheProgram { fun addTwoNumbers(a: Int, b: Int, action: (Int, Int) -> Unit) { // High Level Function with Lambda as Parameter action(a, b) } }

High Level Function with Lambda as Parameter, the function can return a variable

Closures

fun main(args: Array<String>) { val program = Programs() program.reverseAndDisplay("hello", { it.reversed() }) } class Programs { fun reverseAndDisplay(str: String, myFunc: (String) -> String) { // High Level Function with Lambda as Parameter val result = myFunc(str) // it.reversed() ==> str.reversed() ==> "hello".reversed() = "olleh" println(result) } }

it when a parameter a return same type of parameter (String) -> String

With Apply

fun main(args: Array<String>) { var person = Perrson() with(person) { name = "Steve" age = 23 } person.apply { name = "Steve" age = 23 }.startRun() println(person.name) println(person.age) } class Perrson { var name: String = "" var age: Int = -1 fun startRun() { println("Now I am ready to run") } }

Apply

Calls the specified function block with this value as its receiver and returns this value.

With

Calls the specified function block with the given receiver as its receiver and returns its result.