Consider a data class with defined
operation:
data class Foo(
val bar: Int = 0
) {
fun plus(other: Foo) {
return Foo(bar other.bar)
}
}
Now consider a List of these classes
val list: List<Foo>
eg.
val list = listOf(Foo(1), Foo(2), Foo(3))
val summed = list.summed() // Foo(6)
How to define an operation summed
of type List<Foo> -> Foo
in idiomatic way which takes all elements of array and call .plus
operation to create a single element from them?
CodePudding user response:
Solved by
val runningReduceSum = numbers.reduce { sum, item -> sum item }
described in
https://kotlinlang.org/docs/collection-aggregate.html#fold-and-reduce
CodePudding user response:
As @gidds references in their comment, functions to use the
unary type operators, would require an operator keyword on the function.
Also, added the return type for the plus function.
Using extension functions in Kotlin, is the most appropriate manner to add the functionality to a List that you are looking for.
As a word of caution, implementing this function at the top level, would mean that it is in the entire scope of the application. It is generally a good idea to have extension functions scoped inside of an object or class context, just to keep things clean, and not accidentally expose functionality that is intended to be more internal.
data class Foo(val bar: Int = 0) {
operator fun plus(other: Foo): Foo {
return Foo(bar other.bar)
}
}
fun List<Foo>.summed(): Foo {
val sum = fold(0) { acc, value -> acc value.bar }
return Foo(sum)
}
// This function could also be implemented as:
fun List<Foo>.summedAlso(): Foo = reduce(Foo::plus)
val fooList = listOf(
Foo(1), Foo(3), Foo(5)
)
val output = fooList.summed()
println(output) // Foo(9)