I get an error for this fold function;
fun <T> addAll(num: List<T>) : T = num.fold(0, {x,y -> x+y})
saying:
None of the following functions can be called with the arguments supplied.
However if I do:
fun addAll(num: List<Int>) : Int = num.fold(0, {x,y -> x+y})
It works without problems. Is it possible to keep the function generic in order to use it for lists of both integers and doubles?
Unfortunately, Kotlin does not currently allow abstracting over all number types's operators (I believe that's to be able to use primitive numbers in the JVM runtime).
So the best you can get is something like this:
fun <T> addAll(num: List<T>, zero: T, adder: (T, T) -> T) : T =
num.fold(zero, adder)
println(addAll(listOf(1,2,3), 0, Int::plus))
println(addAll(listOf(1.0,2.0,3.0), 0.0, Double::plus))