https://kotlinlang.org logo
i

igor.wojda

01/13/2019, 7:50 PM
I am looking for a way to translate this piece of code from Javascript into Kotlin (I know this is not optimal solution of this problem, but let’s skip this part) So I got something like this
Copy code
private fun maxSubListSum(list: List<Int>, n: Int): Int? {
    if (list.isEmpty()) {
        return null
    }

    var max: Int? = null

    (0..list.size - n).forEach { i ->
        var temp: Int? = null
        (i until (i + n)).forEach { j ->
            if (temp == null) {
                temp = list[j]
            } else {
                temp?.let { temp = it + list[j] }
            }
        }

        temp?.let { localTemp ->
            if(max == null) {
                max = localTemp
            } else {
                max?.let { localMax ->
                    if(localTemp > localMax) {
                        max = temp
                    }
                }
            }
        }
    }

    return max
}
However due
temp
and
max
being
Int?
this
temp
and
max
assignments looks really creepy and requires bunch of
let
. Is there easy way to simplify this 🤔🤔
Copy code
temp?.let { localTemp ->
            if(max == null) {
                max = localTemp
            } else {
                max?.let { localMax ->
                    if(localTemp > localMax) {
                        max = temp
                    }
                }
            }
        }