Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fold left a list of BigDecimal? ("overloaded method + cannot be applied")

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?

like image 604
Jonas Avatar asked Nov 30 '22 16:11

Jonas


1 Answers

The problem is in inital value. The solution is here and is quite simple:

 sum(xs: List[BigDecimal]): BigDecimal = (BigDecimal(0) /: xs) (_ + _)
like image 65
om-nom-nom Avatar answered Dec 15 '22 05:12

om-nom-nom