Kotlin Lambda Expressions
Kotlin Lambda Expressions (Deep Explanation)
In Kotlin, lambda expressions are anonymous functions (functions without a name). They are widely used in higher-order functions, collections, and functional programming.
1. What is a Lambda Expression?
A lambda expression is a block of code that can be assigned to a variable or passed as a parameter.
Syntax
2. Basic Lambda Example
3. Lambda with Return Value
The last expression is automatically returned.
4. Lambda Type Declaration
You can explicitly define the lambda type.
5. it Keyword (Single Parameter)
If a lambda has only one parameter, Kotlin uses it.
6. Lambda as Function Parameter
7. Trailing Lambda Syntax (Very Important)
If the last parameter is a function, write lambda outside parentheses.
8. Lambda with Multiple Statements
9. Lambdas in Collections (Real Usage)
map
filter
reduce
10. Lambda with Receiver
Used in scope functions and DSLs.
Here, this refers to StringBuilder.
11. Anonymous Function vs Lambda
Lambda
Anonymous Function
Anonymous functions allow explicit return statements.
12. return in Lambda (Important Rule)
❌ This is invalid:
✔ Use labels:
13. Inline Lambdas (Performance)
Reduces overhead of lambda objects.
Summary
-
Lambdas are anonymous functions
-
Last expression is returned
-
itfor single parameter -
Widely used with collections and HOFs
-
Core concept in modern Kotlin
