Search code examples
kotlincasting

Kotlin casting Int to Float


I'm trying to learn Kotlin, and I've just made a calculator program from console. I have functions to sum, divide, etc. And when I try to cast integers to float, I get this error:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float

The function is this:

fun divide(a: Int, b: Int): Float {
    return a as Float / b as Float;
}

What am I doing wrong?


Solution

  • To confirm other answers, and correct what seems to be a common misunderstanding in Kotlin, the way I like to phrase it is:

    A cast does not convert a value into another type; a cast promises the compiler that the value already is the new type.

    If you had an Any or Number reference that happened to point to a Float object:

    val myNumber: Any = 6f
    

    Then you could cast it to a Float:

    myNumber as Float
    

    But that only works because the object already is a Float; we just have to tell the compiler.  That wouldn't work for another numeric type; the following would give a ClassCastException:

    myNumber as Double
    

    To convert the number, you don't use a cast; you use one of the conversion functions, e.g.:

    myNumber.toDouble()
    

    Some of the confusion may come because languages such as C and Java have been fairly lax about numeric types, and perform silent conversions in many cases.  That can be quite convenient; but it can also lead to subtle bugs.  For most developers, low-level bit-twiddling and calculation is less important than it was 40 or even 20 years ago, and so Kotlin moves some of the numeric special cases into the standard library, and requires explicit conversions, bringing extra safety.