Lambda_Functions_in_Kotlin
Lambda_Functions_in_Kotlin
---
### Example:
```
val greet = { name: String -> "Hello, $name!" }
println(greet("Alice")) // Output: Hello, Alice!
```
---
### Example:
```
fun performOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
---
### Example:
```
val sayHello = { println("Hello, World!") }
sayHello() // Output: Hello, World!
```
---
### Example:
```
val calculate = { x: Int, y: Int ->
val sum = x + y
val product = x * y
"Sum: $sum, Product: $product"
}
---
### Example:
```
fun repeatAction(times: Int, action: (Int) -> Unit) {
for (i in 1..times) {
action(i)
}
}
repeatAction(3) { println("Hello #$it") }
```
---
### Example:
```
val square = { it: Int -> it * it }
println(square(5)) // Output: 25
```
---
### Example:
```
fun getMultiplier(factor: Int): (Int) -> Int {
return { number -> number * factor }
}
---
### Example:
#### 8.1. **Using `map`**:
```
val numbers = listOf(1, 2, 3, 4)
val squares = numbers.map { it * it }
println(squares) // Output: [1, 4, 9, 16]
```
### Example:
```
val add = fun(x: Int, y: Int): Int {
return x + y
}
---
### Example:
```
val stringBuilderAction: StringBuilder.() -> Unit = {
append("Hello")
append(", World!")
}
val result = StringBuilder().apply(stringBuilderAction)
println(result) // Output: Hello, World!
```
---
## Summary
- **Lambdas** are concise, anonymous functions that improve code
readability.
- They can be used as function arguments, return values, or inline
expressions.
- Kotlin provides many built-in functions like `map`, `filter`, and
`forEach` that use lambdas extensively.
- Use lambdas with receivers for DSL-like code.