java - Kotlin 数据类型是基于原始或非原始 Java 数据类型构建的吗?

我是 Kotlin 的新手,正在研究数据类型。我采用了一个 Int 类型,然后尝试通过说 num as Double 将其转换为 Double,这是一个在 java 中有效的调用(非从语法上讲,但你明白了)。但是,这失败了,说 Int 不能转换为 Double。我假设这是因为它是基于 Integer 类而不是原始 int 数据类型构建的。我是正确的,什么是最有效的转换值的方法?有一个 .toDouble() 函数,但这似乎效率低下且笨拙。

最佳答案

I took an Int type and then tried to cast it as a Double by saying num as Double <...> However, this failed, saying that Int cannot be cast to Double. I am assuming this is because it is built off the Integer class rather than the raw int data type.

不,有两点需要注意:

  • Kotlin 将其数字类型(IntLongDouble 等)定位为不相互嵌套,因此这些类型之间没有子类型关系。这就是为什么转换 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/

相关文章:

java - 为什么在 Java 中实现返回 Unit 的 Kotlin 函数时必须返回 Unit.

file - Kotlin 文件与类。有什么不同?

android - java.lang.NoClassDefFoundError $$inlined

android - 这种类型有一个构造函数,必须在这里初始化 - Kotlin

android - Kotlin 中的 RecyclerView itemClickListener

kotlin - 使用密封类强制编译错误

function - 如何将空值分配给 Kotlin 中的函数类型变量?

android - Kotlin 中的构造函数

kotlin - 如何将可变集合变成不可变集合

android - Unresolved reference DaggerApplicationCo