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)