Reputation: 153
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?
Upvotes: 15
Views: 20796
Reputation: 138
another way
fun divide(a: Int, b: Int) = a.div(b).toFloat()
Upvotes: -1
Reputation: 18537
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.
Upvotes: 22
Reputation: 246
As it states, an Int cannot be cast to a Float. However both kotlin.Int
and kotlin.Float
inherit kotlin.Number
which defines abstract fun toFloat(): Float
. This is what you will need in this scenario.
fun divide(a:Int, b:Int): Float {
return a.toFloat() / b.toFloat()
}
Please refer to https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/to-float.html for more information.
Upvotes: 2
Reputation: 16214
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
}
Upvotes: 5