Introduction
Lambda functions, also known as anonymous functions or function literals, are a concise way to define functions in Kotlin. They can be passed as arguments, returned from other functions, and stored in variables. This chapter will cover the syntax and usage of lambda functions in Kotlin with examples.
Basic Lambda Function
A lambda function in Kotlin is defined using the following syntax:
Syntax
val lambdaName: (ParameterType) -> ReturnType = { parameters -> body }
Example
fun main() {
val greet: (String) -> Unit = { name -> println("Hello, $name!") }
greet("Alice")
}
Explanation:
val greet: (String) -> Unit
: Declares a lambda function namedgreet
that accepts aString
parameter and returnsUnit
(no return value).{ name -> println("Hello, $name!") }
: The lambda function body that prints a greeting message.greet("Alice")
: Calls the lambda function with the argument "Alice".
Output:
Hello, Alice!
Simplified Lambda Function Syntax
If the lambda function has only one parameter, you can use the it
keyword to refer to the parameter, simplifying the syntax.
Example
fun main() {
val greet: (String) -> Unit = { println("Hello, $it!") }
greet("Bob")
}
Explanation:
{ println("Hello, $it!") }
: The lambda function body that prints a greeting message, usingit
to refer to the single parameter.
Output:
Hello, Bob!
Lambda Function with Multiple Parameters
A lambda function can accept multiple parameters. Each parameter is separated by a comma.
Example
fun main() {
val add: (Int, Int) -> Int = { a, b -> a + b }
val result = add(5, 3)
println("Sum: $result")
}
Explanation:
val add: (Int, Int) -> Int
: Declares a lambda function namedadd
that accepts twoInt
parameters and returns anInt
.{ a, b -> a + b }
: The lambda function body that returns the sum ofa
andb
.val result = add(5, 3)
: Calls the lambda function with arguments 5 and 3, storing the result inresult
.
Output:
Sum: 8
Lambda Function with No Parameters
A lambda function can also have no parameters.
Example
fun main() {
val greet: () -> Unit = { println("Hello, Kotlin!") }
greet()
}
Explanation:
val greet: () -> Unit
: Declares a lambda function namedgreet
that accepts no parameters and returnsUnit
.{ println("Hello, Kotlin!") }
: The lambda function body that prints a greeting message.greet()
: Calls the lambda function.
Output:
Hello, Kotlin!
Lambda Function as a Parameter
Lambda functions can be passed as parameters to other functions.
Example
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val doubledNumbers = numbers.map { it * 2 }
println(doubledNumbers)
}
Explanation:
numbers.map { it * 2 }
: Themap
function applies the lambda function{ it * 2 }
to each element of thenumbers
list, doubling each number.println(doubledNumbers)
: Prints the list of doubled numbers.
Output:
[2, 4, 6, 8, 10]
Lambda Function as a Return Value
Lambda functions can be returned from other functions.
Example
fun main() {
val multiplyBy2 = createMultiplier(2)
val result = multiplyBy2(5)
println("Result: $result")
}
fun createMultiplier(factor: Int): (Int) -> Int {
return { it * factor }
}
Explanation:
fun createMultiplier(factor: Int): (Int) -> Int { ... }
: Declares a function namedcreateMultiplier
that returns a lambda function.return { it * factor }
: Returns a lambda function that multiplies its argument by thefactor
.val multiplyBy2 = createMultiplier(2)
: CallscreateMultiplier
with the argument 2, storing the returned lambda function inmultiplyBy2
.val result = multiplyBy2(5)
: Calls the lambda function with the argument 5, storing the result inresult
.
Output:
Result: 10
Inline Lambda Function
You can define a lambda function inline, directly in the function call.
Example
fun main() {
val result = performOperation(5, 3, { a, b -> a + b })
println("Result: $result")
}
fun performOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
Explanation:
performOperation(5, 3, { a, b -> a + b })
: Calls theperformOperation
function, passing an inline lambda function{ a, b -> a + b }
as theoperation
parameter.
Output:
Result: 8
Example Program with Lambda Functions
Here is an example program that demonstrates the use of various forms of lambda functions in Kotlin:
fun main() {
// Basic lambda function
val greet: (String) -> Unit = { name -> println("Hello, $name!") }
greet("Alice")
// Simplified lambda function
val greetSimplified: (String) -> Unit = { println("Hello, $it!") }
greetSimplified("Bob")
// Lambda function with multiple parameters
val add: (Int, Int) -> Int = { a, b -> a + b }
val sum = add(5, 3)
println("Sum: $sum")
// Lambda function with no parameters
val greetNoParams: () -> Unit = { println("Hello, Kotlin!") }
greetNoParams()
// Lambda function as a parameter
val numbers = listOf(1, 2, 3, 4, 5)
val doubledNumbers = numbers.map { it * 2 }
println("Doubled numbers: $doubledNumbers")
// Lambda function as a return value
val multiplyBy2 = createMultiplier(2)
val result = multiplyBy2(5)
println("Result: $result")
// Inline lambda function
val operationResult = performOperation(5, 3, { a, b -> a + b })
println("Operation result: $operationResult")
}
fun createMultiplier(factor: Int): (Int) -> Int {
return { it * factor }
}
fun performOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
Output:
Hello, Alice!
Hello, Bob!
Sum: 8
Hello, Kotlin!
Doubled numbers: [2, 4, 6, 8, 10]
Result: 10
Operation result: 8
Conclusion
In this chapter, you learned about lambda functions in Kotlin, including their syntax and usage for defining anonymous functions, passing them as parameters, returning them from other functions, and using them inline. Understanding how to use lambda functions is essential for writing concise and expressive code in your Kotlin programs.