我想为一个 BigDecimal 列表编写一个简短的函数式求和函数,并尝试使用以下代码:
def sum(xs: List[BigDecimal]): BigDecimal = (0 /: xs) (_ + _)
但是我收到了以下错误信息:
<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) (_ + _)
^
如果我使用Int,那个函数就能正常工作了。我猜测这是因为BigDecimal对+
运算符进行了重载。有什么好的解决方法来处理BigDecimal吗?
reduce
:def sum(xs: List[BigDecimal]) = xs.reduce(_ + _)
。 - Travis BrownList(BigDecimal(1.1), BigDecimal(2.2)).sum
。请注意保持原文意思不变,同时让内容更通俗易懂。 - Luigi Plinge