我是Kotlin的新手,一直在使用数据类型.我采用了Int
类型,然后try 将其转换为Double
,方法是说num as Double
,这是一个在java中有效的调用(从语法上讲不是这样,但您明白这一点).但是,这失败了,因为Int不能强制转换为双精度.我假设这是因为它是基于Integer类构建的,而不是原始的int数据类型.我说的对吗?塑造价值观最有效的方式是什么?虽然有一个.toDouble()
函数,但这似乎效率低下,使用起来也很笨拙.
我是Kotlin的新手,一直在使用数据类型.我采用了Int
类型,然后try 将其转换为Double
,方法是说num as Double
,这是一个在java中有效的调用(从语法上讲不是这样,但您明白这一点).但是,这失败了,因为Int不能强制转换为双精度.我假设这是因为它是基于Integer类构建的,而不是原始的int数据类型.我说的对吗?塑造价值观最有效的方式是什么?虽然有一个.toDouble()
函数,但这似乎效率低下,使用起来也很笨拙.
I took an
Int
type and then tried to cast it as aDouble
by sayingnum as Double
<...> However, this failed, saying that Int cannot be cast toDouble
. I am assuming this is because it is built off theInteger
class rather than the rawint
data type.
No, and there are two important points to note:
Kotlin定位其数值类型(Int
、Long
、Double
等)由于不相互嵌套,这些类型之间有no个亚型关系.这就是为什么演员阵容intNum as Double
在Kotlin 没有成功的原因.这也是为什么这些类型之间没有隐式转换的原因.取而代之的是the numeric conversion is done with the corresponding functions(例如.toDouble()
)
在可能的情况下,Kotlin中的数值类型用法被编译成JVM原语.一些用法需要装箱的类型(例如,可为空的Int?
需要装箱,使用Int
作为类型参数的泛型类型实现也需要装箱),但是编译器会决定它们是否对于每种情况都是必需的.
<...> What is the most efficient way to cast values? There is a
.toDouble()
function, but this seems inefficient and unwieldy.
最有效的方法是使用数字转换函数,如.toDouble()
.实际上,这些函数是intrinsified个,使用它们时没有函数调用开销.它们的编译与javac为Java数值转换或隐式转换生成的结果非常接近.您可以使用Kotlin编译器生成的inspect the bytecode来找出它的内部 struct ,以及特定的转换是否会带来任何开销.
See also: an answer to a similar question, (link)