w3resource

Anonymous Kotlin function: Sum of odd numbers in a list

Kotlin Lambda: Exercise-12 with Solution

Write an anonymous Kotlin function to calculate the sum of all odd numbers in a list.

Sample Solution:

Kotlin Code:

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

    val sumOfOdds: (List<Int>) -> Int = fun(list: List<Int>): Int {
        var sum = 0
        for (number in list) {
            if (number % 2 != 0) {
                sum += number
            }
        }
        return sum
    }

    val oddSum = sumOfOdds(numbers)
    println("Original list of elements: $numbers")
    println("Sum of odd numbers: $oddSum")
}

Sample Output:

Original list of elements: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Sum of odd numbers: 36

Explanation:

In the above exercise -

  • We define an anonymous function called sumOfOdds with the type (List<Int>) -> Int. It takes a list of integers as its parameter and returns the sum of all odd numbers in the list as an integer.
  • Inside the sumOfOdds function, we initialize a variable sum to keep track of the sum, initially set to 0.
  • We iterate through each number in the input list using a for loop. If a number is odd (i.e., not divisible by 2), we add it to the sum variable.
  • In the end, we return the sum of all odd numbers in the list, which represents the final value of sum.

Kotlin Editor:


Previous: Count vowels in a string.
Next: Concatenation of two strings.

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.