I've implemented the plus method on a data class a...
# getting-started
b
I've implemented the plus method on a data class and want to sum up all classes using
Copy code
containers.sumOf { it.dataClassImplementingPlus }
Why isn't this working? What am I looking for? Is there anything better than:
Copy code
containers.map { it.dataClassImplementingPlus }
    .fold(DataClassImplementingPlus()) { acc, el -> acc + el },
1
j
There is no "summable" interface so you don't get these
sumOf
extensions for free. You can implement your own like you did, though. I did exactly that there: https://github.com/joffrey-bion/accounting/blob/main/money%2Fsrc%2FcommonMain%2Fkotlin%2Forg%2Fhildan%2Faccounting%2Fmoney%2FAmount.kt#L93
b
thanks
s
on a side note related to your code, you can use
reduce
instead of
fold
, this way you don't need to create starting accumulator element
b
explodes if the list is empty though, right?
1
j
@Szymon Jeziorski what if the list is empty?
s
oh yes, if you need to cover the empty case as well, then either
fold
or
reduceOrNull
would work depending on the context