我是 Kotlin 的新手,正在研究数据类型。我采用了一个 Int
类型,然后尝试通过说 num as Double
将其转换为 Double
,这是一个在 java 中有效的调用(非从语法上讲,但你明白了)。但是,这失败了,说 Int 不能转换为 Double。我假设这是因为它是基于 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.
不,有两点需要注意:
Kotlin 将其数字类型(Int
、Long
、Double
等)定位为不相互嵌套,因此这些类型之间没有子类型关系。这就是为什么转换 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 数字转换或隐式转换生成的内容非常接近。您可以inspect the bytecode Kotlin 编译器生成的内容是为了找出它的底层内容以及特定的转换是否会引入任何开销。
另请参阅:对类似问题的回答,(link)
https://stackoverflow.com/questions/45420806/