Practice Time: Lambdas

 A Lambda is an expression that makes a function, instead of declaring a named function, we declare a function that has no name


/** File:            Main.kt
* Programmer: Nolverto Urias Obeso
* Creation Date: 06/16/2023
* Description: Learn how to use lambdas
*/




fun main() {
// Lambda is a function that has no name

// Example 1
val swim = { println("swimming \n") }
swim() // Lambda function is called using ()

//Lambdas can take argumets just like named functions
var dirty = 20
// Arguments go on the left hand side of whats called a function arrow
// The body of the lambda goes after the function arrow
val waterFilter = {dirty:Int -> dirty/2} // This function takes an Int argument and resturns the result of dividing it by two
println(waterFilter(dirty)) // Returns and print the result of the lambda function

// waterFilter2 can be any function that takes an Int and returns an Int
val waterFilter2: (Int) -> Int = {dirty -> dirty/2}
println(waterFilter2(dirty))

// This is a compact function
fun feedFish(dirty: Int) = dirty + 10
println(feedFish(dirty))

// The real power of lambda happens when we make higher-order functions
// A higher order function is just any function that takes a function as the argument
// Note: make sure operation is the last argument
fun updateDirty(dirty: Int, operation:(Int) -> Int ) : Int{
return operation(dirty)
}


dirty = updateDirty(dirty, waterFilter2)
println(dirty)
// Since feedFish is a name function and not a lambda, you'll need to use a double colon to parse it
// This way Kotlin knows you're not trying to call feedFish and it let you parse a reference
// When you combine higher order functions with lambdas, Kotlin has a special syntax, its called the last parameter called syntax

dirty = 111
dirty = updateDirty(dirty, ::feedFish)
println(dirty)


// this time we parse a lambda as an argument for the parameter operation
// The interesting thing here, its that a lambda is an argument to updateDirty, but since we're parsing it
// as the last parameter, we dont have to put it inside the function parenthesis
dirty = updateDirty(dirty){dirty ->
dirty + 50
}
println(dirty)

// Here you can see we're just parsing the lambda as an argument updateDirty.
// Using this syntax, we can define functions that look like they're built-in to the language
dirty = updateDirty(dirty, {dirty -> dirty + 30})
println(dirty)

}

fun swim(){

}

Comments

Popular posts from this blog