I want to write a short functional sum-function for a List of BigDecimal and tried with:
def sum(xs: List[BigDecimal]): BigDecimal = (0 /: xs) (_ + _)
But I got this error message:
<console>:7: error: overloaded method value + with alternatives:
(x: Int)Int <and>
(x: Char)Int <and>
(x: Short)Int <and>
(x: Byte)Int
cannot be applied to (BigDecimal)
def sum(xs: List[BigDecimal]): BigDecimal = (0 /: xs) (_ + _)
^
If I use Int instead, that function works. I guess this is because BigDecimal's operator overloading of +
. What is a good workaround for BigDecimal?
The problem is in inital value. The solution is here and is quite simple:
sum(xs: List[BigDecimal]): BigDecimal = (BigDecimal(0) /: xs) (_ + _)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With