# Kotlin Program: Lambda expression for calculating the average of numbers

## Kotlin Lambda: Exercise-4 with Solution

Write a Kotlin program that implements a lambda expression to calculate the average of a list of numbers.

Sample Solution:

Kotlin Code:

``````fun main() {
val numbers = listOf(10, 20, 30, 40, 50, 60, 70)

val average: (List) -> Double = { nums ->
if (nums.isEmpty()) {
throw IllegalArgumentException("List cannot be empty")
}
val sum = nums.sum()
sum.toDouble() / nums.size
}

val result = average(numbers)
println("Average: \$result")
}
```
```

Sample Output:

```Average: 40.0
```

Explanation:

In the above exercise -

• First we declare a lambda expression average of type (List<Int>) -> Double. The lambda expression takes a list of integers 'nums' as an input parameter.
• Inside the lambda expression, we first check if the 'nums' list is empty. If it is, we throw an IllegalArgumentException. Otherwise, we calculate the sum of the numbers using the "sum()" function and store it in the sum variable. To calculate the average, we divide the sum by the list size.
• In the "main()" function, we invoke the average lambda expression by passing the 'numbers' list as an argument and store the result in the result variable. The average is then printed using println.

Kotlin Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿