Why doesn't Kotlin do automatic injection molding?
var a : Double
a = Math.sin(10) // error: the integer literal does not conform to the expected type Double
a = Math.sin(10.0) //This compiles successfully
println(a)
Why doesn't kotlin do an implicit type conversion and forces us to pass in the exact data type?
fun sin(value: Double): Double // at kotlin documentation
source to share
We all know that Kotlin has both non-nullable Int
and nullable Int?
.
When we use Int?
, this happens: in fact, Kotlin "boxes" of JVM primitives when Kotlin needs a null reference, as it aims to remove the danger of null references from code.
Now let's look at this: (assuming this is compiled code)
val a: Int? = 1
val b: Long? = a
Kotlin does not perform implicit type conversions because it does. If Kotlin did implicit type conversions, there b
should be 1
. but since it a
is a box Int
and a b
is a box Long
, it gives and collides because the operator checks and checks the other part as . a == b
false
==
equals()
Long
equals()
Long
Check the documentation:
source to share
Kotlin does not allow implicit conversions to numeric types. There is a misconception that implicit "no harm, no foul" conversions ... which is wrong.
The process in Java for implicit conversions is more complicated than you might think, reading the docs to see what this entails. And then you can try to analyze all the cases that could go wrong.
Kotlin doesn't want the compiler to guess your intent, so it makes everything explicit in the language, including numeric type conversions. As explained in the Kotlin docs for Explicit Conversions , it says clearly:
Because of the different representations, smaller types are not subtypes of larger ones. [...] As a consequence, smaller types are NOT implicitly converted to larger types. [...] We can use explicit conversions to expand numbers.
And the documentation shows one such example where things can go wrong, but there are many others.
And you cannot just convert one numeric type to another, as pointed out here in the wrong comments and answers. This will only lead to a nice runtime error. Instead, look at numeric conversion functions like toInt()
and toDouble()
found on numeric types such as number class .
The explanation is part of Kotlin's personality and is not planned to be changed.
source to share
Automatic type casting for numeric types can result in loss of precision. Just consider the following java code:
double hoursSinceUnixEra = System.currentTimeMillis()/1000/60/60;
The goal was not to cut the result down to a full hour, although it does compile without warning in Java.
val hoursSinceUnixEra = System.currentTimeMillis()/1000/60/60;
someObject.doubleValue = hoursSinceUnixEra
Above Kotlin code will not compile due to implicit casting.
This type of problem can be very difficult to find and fix, and this is the reason for this solution. You can still explicitly convert the type:
val value = 3
Math.sin(value.toDouble())
source to share