Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin casting int to float

Tags:

casting

kotlin

I'm triying to learn Kotlin , and I just made a calculator program from console. I have functions to sum , divide etc. And when I try to cast to 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 I'm doing wrong?

like image 837
Juan Celaya Avatar asked Dec 31 '22 04:12

Juan Celaya


2 Answers

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.

like image 55
gidds Avatar answered Jan 04 '23 16:01

gidds


The exception's stacktrace pretty much explained why the cast can never succeed:

java.lang.Integer cannot be cast to java.lang.Float

Neither of the classes java.lang.Integer and java.lang.Float is extending the other so you can't cast java.lang.Integer to java.lang.Float (or vice versa) with as.

You should use .toFloat().

fun divide(a: Int, b: Int): Float {
    return a.toFloat() / b
}
like image 33
Giorgio Antonioli Avatar answered Jan 04 '23 17:01

Giorgio Antonioli