Kotlin Sum of positive number

Our task is to find in Kotline Sum of positive number in defined function. We written below code but getting compilation error. Hence need expertise advice for it -

import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*

fun sum(nums:Array<Int>,add: (acc:Int,ele:Int) -> Int):Int {
      var res=0
    for(i in nums){
        res = add(res,i)
    return res

--Editable Code---
fun getLambda(): (acc:Int,ele:Int) -> Int {
    var lambda = { acc: Int, ele: Int -> acc + ele }
    return lambda

fun main(args: Array<String>) {
    val numsCount = readLine()!!.trim().toInt()

    val nums = Array<Int>(numsCount, { 0 })
    for (i in 0 until numsCount) {
        val numsItem = readLine()!!.trim().toInt()
        nums[i] = numsItem
    val lambda = getLambda()
    val result = sum(nums,lambda)

Maybe you should tell us what is the compilation error you get.

I can find any compilation error in your code:

fun sum(nums: Array<Int>, add: (acc: Int, ele: Int) -> Int): Int {
    var res = 0
    for (i in nums) {
        res = add(res, i)
    return res

fun getLambda(): (acc: Int, ele: Int) -> Int {
    var lambda = { acc: Int, ele: Int -> acc + ele }
    return lambda

fun main() {
    val nums = arrayOf(1,2,3,4,5) // Simplified to run in the playground

    val lambda = getLambda()
    val result = sum(nums, lambda)

yes but now it is fine but desire output not coming.

Our task is

Write a lambda expression that can be used to find the sum of positive numbers in the defined function sum.

var lambda = in this seems we need to call sum function

can we try with

var lambda = sum(acc, ele)

I’m guessing that you are only supposed to sum positive numbers. That means that you need to check if ele is greater than 0 before adding it.

This sounds like homework so I’ll let you figure out the exact code :wink:

1 Like