0% found this document useful (0 votes)
13 views

Lambda_Functions_in_Kotlin

Lambda functions in Kotlin are anonymous functions that enhance code readability and can be passed to higher-order functions. They can be defined with various syntaxes, used as function parameters, and even returned from functions. Kotlin also offers built-in functions like `map`, `filter`, and `forEach` that utilize lambdas for more expressive coding.

Uploaded by

HASEEB KHAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lambda_Functions_in_Kotlin

Lambda functions in Kotlin are anonymous functions that enhance code readability and can be passed to higher-order functions. They can be defined with various syntaxes, used as function parameters, and even returned from functions. Kotlin also offers built-in functions like `map`, `filter`, and `forEach` that utilize lambdas for more expressive coding.

Uploaded by

HASEEB KHAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lambda Functions in Kotlin

# Lambda Functions in Kotlin

Lambda functions are anonymous functions that can be treated as


values and passed to higher-order functions. They are concise and
help improve code readability, especially for small blocks of logic. In
this document, we will explore various ways lambda functions can be
used in Kotlin, with detailed examples.

---

## 1. **Basic Lambda Function**


A lambda function is defined using the `{}` syntax. You can assign it
to a variable or pass it directly to a function.

### Example:
```
val greet = { name: String -> "Hello, $name!" }
println(greet("Alice")) // Output: Hello, Alice!
```

---

## 2. **Using Lambdas as Function Parameters**


Lambda functions can be passed as arguments to other functions,
making your code more modular and reusable.

### Example:
```
fun performOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}

val sum = performOperation(5, 3) { x, y -> x + y }


println(sum) // Output: 8
```

---

## 3. **Lambdas with No Parameters**


A lambda function can also have no parameters.

### Example:
```
val sayHello = { println("Hello, World!") }
sayHello() // Output: Hello, World!
```

---

## 4. **Lambda with Multiple Statements**


If a lambda contains multiple statements, the last statement is the
return value.

### Example:
```
val calculate = { x: Int, y: Int ->
val sum = x + y
val product = x * y
"Sum: $sum, Product: $product"
}

println(calculate(3, 4)) // Output: Sum: 7, Product: 12


```

---

## 5. **Using Lambdas with Higher-Order Functions**


Higher-order functions accept functions as parameters or return
them.

### Example:
```
fun repeatAction(times: Int, action: (Int) -> Unit) {
for (i in 1..times) {
action(i)
}
}
repeatAction(3) { println("Hello #$it") }
```

---

## 6. **Using `it` for Single Parameters**


If a lambda has only one parameter, you can use `it` instead of
explicitly naming the parameter.

### Example:
```
val square = { it: Int -> it * it }
println(square(5)) // Output: 25
```

---

## 7. **Returning Lambdas from Functions**


A function can return a lambda function.

### Example:
```
fun getMultiplier(factor: Int): (Int) -> Int {
return { number -> number * factor }
}

val double = getMultiplier(2)


println(double(4)) // Output: 8
```

---

## 8. **Inline Lambdas with Built-In Functions**


Kotlin provides many built-in higher-order functions like `map`,
`filter`, and `forEach` that use lambdas.

### 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]
```

#### 8.2. **Using `filter`**:


```
val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // Output: [2, 4]
```

#### 8.3. **Using `forEach`**:


```
numbers.forEach { println(it) }
```
---

## 9. **Anonymous Functions vs Lambdas**


An anonymous function is similar to a lambda but has a more explicit
syntax.

### Example:
```
val add = fun(x: Int, y: Int): Int {
return x + y
}

println(add(3, 4)) // Output: 7


```

---

## 10. **Lambdas with Receivers**


Lambdas can operate as extensions for specific objects.

### 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.

Explore these examples to better understand how lambdas can


simplify your Kotlin code and make it more expressive!

You might also like