w3resource

Kotlin Program: Lambda expression for calculating the average of numbers


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


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should be familiar with the following concepts:

  • Lambda Expressions: A lambda expression is an anonymous function in Kotlin that can be assigned to variables and passed as arguments.
  • Lists in Kotlin: Kotlin provides a built-in List collection, which allows storing multiple elements of the same type.
  • List Functions: The sum() function computes the sum of all elements in a list, and size gives the total number of elements.
  • Exception Handling: The program throws an IllegalArgumentException if the list is empty to prevent division by zero.
  • Type Conversion: To get an accurate average, the sum is converted to a Double before division.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Create a lambda expression that takes a list of integers as input and returns a double.
  • Hint 2: Check if the list is empty before performing calculations to avoid division errors.
  • Hint 3: Use the sum() function to get the total sum of the list elements.
  • Hint 4: Convert the sum to a Double before dividing it by the list size to ensure the correct result.
  • Hint 5: Call the lambda by passing a list of numbers and print the result using println().

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:


Previous: Lambda expression to check if a number is even.
Next: Filter list of strings with lambda expression.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.