简体   繁体   English

如何在 Kotlin 中使用原始类型?

[英]How to use primitive types in Kotlin?

Kotlin automatically forces us to use wrappers like Float, Double, Int, Boolean, etc. Kotlin 自动强制我们使用 Float、Double、Int、Boolean 等包装器。

But sometimes, for performance and memory reasons, we need to use primitive types.但有时,出于性能和内存方面的原因,我们需要使用原始类型。

I am aware that this can be done if you use special arrays such as IntArray, DoubleArray, FloatArray, etc.我知道如果您使用特殊数组(例如 IntArray、DoubleArray、FloatArray 等),则可以这样做。

But what about single primitives in a variable?但是变量中的单个原语呢?

Kotlin doesn't use wrapper types for non-nullable types, such as Int or Float - those will get compiled into int and float . Kotlin 不为不可空类型使用包装器类型,例如IntFloat - 这些将被编译为intfloat However, if you use nullable types, such as Int?但是,如果您使用可空类型,例如Int? or Float?还是Float? , Kotlin will use wrapper types - Integer and Float - to be able to represent null values. , Kotlin 将使用包装器类型 - IntegerFloat - 来表示空值。 Using non-nullable primitive types in Kotlin will not lead to unnecessary allocations.在 Kotlin 中使用不可为 null 的原始类型不会导致不必要的分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM