Kotlin Cast Int浮动 [英] Kotlin casting int to float
问题描述
我正在努力学习Kotlin,我只是从控制台制作了一个计算器程序. 我有求和,除等的函数.当我尝试将其强制转换为浮点数时,出现此错误:
线程"main"中的异常java.lang.ClassCastException:无法将java.lang.Integer强制转换为java.lang.Float
函数是这样的:
fun divide(a:Int,b:Int):Float{
return a as Float / b as Float;
}
我做错了什么?
要确认其他答案并更正Kotlin中似乎常见的误解,我想表达的意思是:
强制类型转换不会将值转换为另一种类型;强制转换向编译器保证该值已经 是新类型.
如果您有Any
或Number
引用碰巧指向了Float
对象:
val myNumber: Any = 6f
然后您可以将其投放到Float:
myNumber as Float
但这只能起作用,因为该对象已经是一个Float
;我们只需要告诉编译器.这不适用于其他数字类型.以下将给出ClassCastException
:
myNumber as Double
要转换数字,您无需使用强制转换;您使用一种转换功能,例如:
myNumber.toDouble()
由于诸如C和Java之类的语言对数字类型相当宽松,并且在许多情况下执行静默转换,可能会引起一些困惑.那可能很方便.但这也会导致细微的错误.对于大多数开发人员而言,低级位纠缠和计算比40甚至20年前要重要的多,因此Kotlin将一些数字特例转移到标准库中,并且需要进行显式转换,从而带来了额外的安全性. /p>
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?
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.
这篇关于Kotlin Cast Int浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!