0
0
Kotlinprogramming~5 mins

Lambda syntax and declaration in Kotlin

Choose your learning style9 modes available
Introduction
Lambdas let you write small pieces of code that you can pass around and use later, like a recipe you can share and follow anytime.
When you want to quickly define a small function without naming it.
When you need to pass a simple action to another function, like sorting or filtering a list.
When you want to make your code shorter and easier to read by avoiding full function declarations.
Syntax
Kotlin
val lambdaName: (InputType) -> ReturnType = { parameter -> body }
The part before '=' declares the lambda type: input and output types.
Inside the curly braces, 'parameter -> body' defines what the lambda does.
Examples
A lambda that takes a name and prints a greeting.
Kotlin
val greet: (String) -> Unit = { name -> println("Hello, $name!") }
A lambda that takes a number and returns its square.
Kotlin
val square: (Int) -> Int = { number -> number * number }
A lambda with no parameters that prints 'Hello!'. Kotlin infers the type here.
Kotlin
val printHello: () -> Unit = { println("Hello!") }
Sample Program
This program declares a lambda that multiplies two numbers and then prints the result.
Kotlin
fun main() {
    val multiply: (Int, Int) -> Int = { a, b -> a * b }
    val result = multiply(4, 5)
    println("4 times 5 is $result")
}
OutputSuccess
Important Notes
If a lambda has only one parameter, you can use 'it' instead of naming it.
Kotlin can often infer the lambda type, so you can omit explicit type declarations.
Lambdas are useful for passing behavior to functions like 'map', 'filter', and 'forEach'.
Summary
Lambdas are small unnamed functions you can store in variables.
They use curly braces with parameters and an arrow to separate the body.
Lambdas make your code shorter and more flexible.