Is java.lang.Math compatible with kotlin.math?

I studied Kotlinand ran into this problem in the Math class:

java.lang.Mathand kotlin.mathincompatible. This is a little inconvenient and confusing for me, as it Kotlinclaims to be 100% compatible with Java. Maybe it's just me who feels that this is confusing, but I would like to hear the opinion of the community to confirm whether I feel right.

The problem is rounding the number. Please observe the following simple Kotlincode:

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)}")
}

Conclusion:

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 rounded to the value long, and Kotlin, on the contrary, is rounded to the value kotlin.Double. The implementation of the Math classes in two different languages ​​is different and can it cause confusion, since both of them are aimed at the JVM?

thank

+4
1

kotlin.math.round :

x , .

, 152.5 152 153, , , .. 152.

, Java round :

[ int, ] , .

kotlin.math.round , Java Math.rint(x).

+5

Source: https://habr.com/ru/post/1695018/


All Articles