kotlinfunctional-programming

What is the cleanest way to sum elements in a list except the last one in Kotlin?


The question is mostly out of curiosity, and because I've barely scratched the surface with functional idioms. I have a list of Ints where the last one is the checksum, so in order to verify it I need to sum together all the other ones. So far I came up with this:

val checksum = list.dropLast(1).sum()

Is it possible to do better?


Solution

  • Probably something alike this might also work; in terms of selecting elements vs. dropping one:

    val checksum = list.takeWhile{ list.indexOf(it) < list.lastIndex }.sum()
    

    Or a whole lot more simple formulated:

    val checksum = list.sum().minus(list.last())
    

    What suits better merely depends if one later still needs to use that list for something else.