BigDecimal operator overloading with java method


#1

A sample expressions
BigDecimal(100)*BigDecimal(10).divide(BigDecimal(30),2,RoundingMode.HALF_UP)
Instinctively,we expect 33.33 but now result is 33.00,so why compiler do not execute operator overloading times method first.


#2

Because the .-operator has a higher precedence than the *-operator. Operator precedence can only work properly if you use basic mathematical operators. Normal function calls like .divide(...) have a higher precedence.

This example has the same problem

import kotlin.math.*
fun main() {
//sampleStart
fun Int.abs() = abs(this)
println(-5.abs())
//sampleEnd
}

Here the minus has a lower precedence than the function call Int.abs(). Therefore we calculate 5.abs() first and only then take the negative.