Kotlin casting int to float

核能气质少年 提交于 2020-05-16 07:12:49

问题


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?


回答1:


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.




回答2:


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
}



回答3:


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.




回答4:


another way

fun divide(a: Int, b: Int) = a.div(b).toFloat()


来源:https://stackoverflow.com/questions/61129343/kotlin-casting-int-to-float

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!