Just porting the code to Kotlin only marginally improves the readability:

val a = BigDecimal . valueOf ( 5.8 ) val b = BigDecimal . valueOf ( 5.6 ) val sub = a . subtract ( b ) assertThat ( sub ). isEqualTo ( BigDecimal . valueOf ( 0.2 ))

Note that in Kotlin, floating-points numbers are doubles by default.

In order to make the API more fluent and thus the code more readable, two valuable Kotlin features can be applied.

The first one is extension method (I’ve already showed their use in a former post to improve logging with SLF4J. Let’s use it here to easily create BigDecimal objects from Double :

fun Double . toBigDecimal (): BigDecimal = BigDecimal . valueOf ( this ) val a = 5.8 . toBigDecimal () // Now a is a BigDecimal

The second feature - coupled with method extension, is operator overloading. Kotlin sits between Java where operator overloading is impossible, and Scala where every operator can be overloaded (I’m wondering why there aren’t already any emoticons library): only some operators can be overloaded, including those from arithmetics - + , - , * and / .

They can be overriden quite easily, as shown here:

operator fun BigDecimal . plus ( a : BigDecimal ) = this . add ( a ) operator fun BigDecimal . minus ( a : BigDecimal ) = this . subtract ( a ) operator fun BigDecimal . times ( a : BigDecimal ) = this . multiply ( a ) operator fun BigDecimal . div ( a : BigDecimal ) = this . divide ( a ) val sub = a - b

Note this is already take care of in Kotlin’s stdlib.

The original snippet can now be written like this:

val a = 5.8 . toBigDecimal () val b = 5.6 . toBigDecimal () assertThat ( a - b ). isEqualTo ( 0.2 . toBigDecimal ())