如何折叠BigDecimal列表?("重载方法+无法应用")

Jon*_*nas 4 scala bigdecimal fold

我想为BigDecimal列表编写一个简短的函数和函数,并尝试使用:

def sum(xs: List[BigDecimal]): BigDecimal = (0 /: xs) (_ + _)
Run Code Online (Sandbox Code Playgroud)

但我收到此错误消息:

<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) (_ + _)
                                                                ^
Run Code Online (Sandbox Code Playgroud)

如果我改为使用Int,那么该函数是有效的.我猜这是因为BigDecimal的运算符重载了+.BigDecimal有什么好的解决方法?

om-*_*nom 16

问题在于初始价值.解决方案在这里非常简单:

 sum(xs: List[BigDecimal]): BigDecimal = (BigDecimal(0) /: xs) (_ + _)
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一下,大多数scala集合都有方法`sum`所以在+操作的特殊情况下你可以简单地写`List(BigDecimal(1),BigDecimal(3)).sum`来得到`scala.math.BigDecimal = 4 ` (2认同)