Introduction
Lambdas let you send small pieces of code to functions. This makes your code flexible and easy to change.
Lambdas let you send small pieces of code to functions. This makes your code flexible and easy to change.
fun functionName(action: (Type) -> ReturnType) { // use action inside val value: Type = TODO() val result = action(value) // do something with result }
The lambda is passed as a parameter inside parentheses.
The lambda type shows input and output types: (Type) -> ReturnType.
fun greet(action: (String) -> Unit) { action("Hello") } greet { message -> println(message) }
fun calculate(x: Int, operation: (Int) -> Int): Int { return operation(x) } val result = calculate(5) { it * 2 } println(result)
This program shows how to pass lambdas to add and multiply two numbers. It prints the results.
fun applyOperation(x: Int, y: Int, operation: (Int, Int) -> Int): Int { return operation(x, y) } fun main() { val sum = applyOperation(4, 5) { a, b -> a + b } val product = applyOperation(4, 5) { a, b -> a * b } println("Sum: $sum") println("Product: $product") }
You can use the 'it' keyword if the lambda has only one parameter.
Lambdas make your functions more reusable and clear.
Lambdas are small blocks of code you can pass to functions.
They help make your code flexible and shorter.
Use lambdas to customize what a function does without changing the function itself.
fun operate(x: Int, action: (Int) -> Int): Int {
return action(x)
}
fun main() {
val result = operate(5) { it * 2 }
println(result)
}fun applyOperation(x: Int, op: (Int) -> Int) {
op(x)
}
fun main() {
applyOperation(3) { println(it * 3) }
}filterAndTransform that takes a list of integers and two lambdas: one to filter the list and one to transform each filtered item. Which of these function signatures correctly allows passing both lambdas?Pass the test and this pattern moves unknown