Sum of Array

It in fact could be also adjusted with recursive clause like that:

fun Array<*>.sumByInt(): Int{
  return this.sumBy {
            when(it) {
                is Int -> it
                is IntArray -> it.sum()
                is Array<*> -> it.sumByInt() // fix by @dalewking
                else -> error("some error message")
            }
        }
}

val result = array.sumByInt()

I like it better then my solution. Kotlin has a lot of convenient extensions and I missed sumBy which has inlined for-loop. I am thinking a lot in terms of Java 8 lambdas, which work different from kotlin inlined lambdas. In Java 8 objects are not created when one calls lambda since it utilized invokedynamic which is still not available in kotlin. But in any case, sumBy looks better and avoids number wrapping in array.

1 Like