It's been a few days since I started using Kotlin as a hobby, and I'm impressed with the careful support for Java's itch. BigDecimal arithmetic is one of them.
Numerical operations are often required in business applications, but Double is not usable, so BigDecimal is an option. And this BigDecimal operation is extremely unreadable.
BigDecimalBasicSample.kt
/**
* BigDecimal coding style : (a + b) / 2
*/
fun main(args: Array<String>) {
val a = BigDecimal.ONE
val b = BigDecimal.TEN
// Java style
println(a.add(b).divide(BigDecimal.valueOf(2L), RoundingMode.HALF_EVEN))
// Kotlin basic style
println((a + b) / 2.toBigDecimal())
}
Java is terrible.
Kotlin is very easy to read because it can apply arithmetic operators, but I'm still dissatisfied with 2.toBigDecimal ()
.
BigDecimalCustomSample.kt
/** custome operator BigDecimal / Long */
operator fun BigDecimal.div(other : Long) : BigDecimal = this / other.toBigDecimal()
/**
* BigDecimal coding style : (a + b) / 2
*/
fun main(args: Array<String>) {
val a = BigDecimal.ONE
val b = BigDecimal.TEN
// Java style
println(a.add(b).divide(BigDecimal.valueOf(2L), RoundingMode.UP))
// Kotlin custom oeprator style
println((a + b) / 2)
}
Readability is improved by implementing the original operator of BigDecimal / Long
.
In Kotlin, operators are equivalent to calling a given method. In Operator overloading, each operator and its corresponding The method to do is shown. The following is an excerpt of the operator overloading.
Expression | Translated to |
---|---|
a + b |
a.plus(b) |
a - b |
a.minus(b) |
a * b |
a.times(b) |
a / b |
a.div(b) |
a % b |
a.rem(b) , a.mod(b) (deprecated) |
a..b |
a.rangeTo(b) |
By implementing methods such as plus
with ʻoperator fun`, you can define your own operators between arbitrary classes.
The operator implementation is in BigDecimals.kt included in kotlin-stdlib It is described. Excerpt from the implementation of division "/" as a sample. You can see that BigDecimal # divide
is used and RoundingMode.HALF_EVEN
is used as an argument.
BigDecimals.kt
/**
* Enables the use of the `/` operator for [BigDecimal] instances.
*
* The scale of the result is the same as the scale of `this` (divident), and for rounding the [RoundingMode.HALF_EVEN]
* rounding mode is used.
*/
@kotlin.internal.InlineOnly
public inline operator fun BigDecimal.div(other: BigDecimal): BigDecimal = this.divide(other, RoundingMode.HALF_EVEN)
Recommended Posts