Search code examples
type-conversionkotlinimplicit-conversion

kotlin - automatic conversion of numeric types


In java, we can assign int to double, for example double x = 123;

In kotlin, we got a compiled error.

Question: Can we enable automatic conversion feature in kotlin? Why kotlin don't have this feature by default?

var x: Double = 123; // ERROR

One more example:

fun foo(x: Double) { }

fun main(args: Array<String>) {
   foo(123.0);  // OK 
   foo(123);    // ERROR
}

UPDATE:

the literal 123 can be automatically converted to Short or Long at compile time. But it will not be converted to Float or Double.

fun fooShort(x: Short) {}
fun fooInt(x: Int)     {}
fun fooLong(x: Long)   {}


fun main(args: Array<String>) {
    fooShort(123)  // OK
    fooInt(123)    // OK
    fooLong(123)   // OK
}

Solution

  • No. This isn't going to happen. As kotlin is strongly typed meaning types aren't coerced implicitly. You need an explicit type conversion. From the Kotlin reference for Explicit number conversions it is stated:

    Due to different representations, smaller types are not subtypes of bigger ones. [...] As a consequence, smaller types are NOT implicitly converted to bigger types. [...] We can use explicit conversions to widen numbers.