I was learning Kotlin
and ran into this issue in Math class:
The java.lang.Math
and kotlin.math
are not compatible. This is for me a little bit awkward and confusing since Kotlin
claims that it is 100% compatible with Java
. Maybe this is only me who is feeling it is confusing, but I would like to hear community opinion to confirm if my feeling is correct.
The issue is the rounding of a number. Please observe the following simple Kotlin
code:
fun main(args: Array<String>) {
val neg = -152.5
val kotlinAbsoluteValue = kotlin.math.abs(neg)
val javaAbsoluteValue = java.lang.Math.abs(neg)
println("Original Variable: $neg")
println("Absolute Value in Java: $javaAbsoluteValue")
println("Absolute Value in Kotlin: $kotlinAbsoluteValue")
println("Rounding kotlinAbsoluteValue in Java: ${java.lang.Math.round(kotlinAbsoluteValue)}")
println("Rounding kotlinAbsoluteValue in Kotlin: ${kotlin.math.round(kotlinAbsoluteValue)}")
println("Rounding javaAbsoluteValue in Java: ${java.lang.Math.round(javaAbsoluteValue)}")
println("Rounding javaAbsoluteValue in Kotlin ${kotlin.math.round(javaAbsoluteValue)}")
}
Output:
Original Variable: -152.5
Absolute Value in Java: 152.5
Absolute Value in Kotlin: 152.5
Rounding kotlinAbsoluteValue in Java: 153
Rounding kotlinAbsoluteValue in Kotlin: 152.0
Rounding javaAbsoluteValue in Java: 153
Rounding javaAbsoluteValue in Kotlin 152.0
I see that Java Math is rounding up to long
value and Kotlin in contrast rounding down to kotlin.Double
value. The implementation of Math classes in two different languages are different and wouldn't this cause confusion since they both target JVM?
Thanks