Skip to content

Instantly share code, notes, and snippets.

@xingstarx
Created January 5, 2018 07:20
Show Gist options
  • Save xingstarx/9559f7437b25ed2be70d44420cb29fe1 to your computer and use it in GitHub Desktop.
Save xingstarx/9559f7437b25ed2be70d44420cb29fe1 to your computer and use it in GitHub Desktop.
Koltin 扩展sumByBigDecimal方法

Iterable提供了一个sumByDouble方法,但是对于BigDecimal类型的Iterable运算的结果实在是差强人意,看下面这段代码的运行结果:

var list = listOf<BigDecimal>(BigDecimal(10.21.toString()), BigDecimal(8.21.toString()), BigDecimal(12.21.toString()))
    var repaymentAmount = BigDecimal(list.sumByDouble { it.toDouble() })
//    var repaymentAmount = list.sumByBigDecimal { it }
    println("repaymentAmount == $repaymentAmount")

输出的是repaymentAmount == 30.63000000000000255795384873636066913604736328125

仿照sumByDouble方法扩展了一个新的方法sumByBigDecimal,做了部分修改,具体如下

public inline fun <T> Iterable<T>.sumByBigDecimal(selector: (T) -> BigDecimal): BigDecimal {
    var sum: BigDecimal = BigDecimal.ZERO
    for (element in this) {
        sum = sum.add(selector(element))
    }
    return sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment