简体   繁体   English

Kotlin 的 'const val num = 1' 的类型是什么? 他们如何定义它?

[英]What is the type of 'const val num = 1' of Kotlin? And how are they able to define it?

Mostly, I use Int , Double and String , Char .大多数情况下,我使用IntDoubleStringChar Recently, I got interested in saving memory and I realized even small amount of bytes can be much larger and it affects the program and even the mobile speed and battery life.(Especially, data resources of its memory)最近对保存memory产生了兴趣,意识到即使是很小的字节也可以大得多,它会影响程序甚至移动速度和电池寿命。(特别是它的内存数据资源)

So, I am trying to use Byte , Short when the data doesn't need to store big numbers.所以,当数据不需要存储大数字时,我尝试使用ByteShort For example, byte for -128 ~ 127 , Short for -32,768 ~ 32,767 .例如,字节为-128 ~ 127 ,简写为-32,768 ~ 32,767

Is it a good idea?这是个好主意吗?

And My main question is I want to know the data type of const val in Kotlin since it automatically defines the datatype.我的主要问题是我想知道 Kotlin 中 const val 的数据类型,因为它会自动定义数据类型。

const val THIS_IS_STRING = "HelloWorld"
const val THIS_IS_CHAR = 'C'
const val NUMBER_1 = -124
const val NUMBER_2 = 31000
const val NUMBER_3 = 1000000
const val NUMBER_4 = 1232188777777344444
const val NUMBER_5 = 29128812312732881231273712
const val NUMBER_6 = 0.423
const val NUMBER_7 = 0.2121222222441
const val NUMBER_8 = 0.813881281237123991827312324
const val NUMBER_9 = 0.5123090982307037412398190092340239423094803820432423423209823092342342348209384023984023480923840923840009930923094029848901

What are the data types of them(The numbers)?它们的数据类型是什么(数字)?

Or should I define like these for saving the resources?还是我应该像这样定义以节省资源? Or I don't need to?还是我不需要?

const val MIN:Byte = -124
const val MID:Short = 31000
const val MAX:Int = 1000000
...
``

It is dependent on you whether you want to provide data type allocation to kotlin or self.是否要为 kotlin 或 self 提供数据类型分配取决于您。 If your saving the values by providing resource type.如果您通过提供资源类型来保存值。 You can save data or you can depend on the kotlin.您可以保存数据,也可以依赖 kotlin。

But if your saving the data i will advice you to provide the data type:但是,如果您保存数据,我会建议您提供数据类型:

Let's take this as an example for you:让我们以此为例:

fun main() {
    var b: Any = 124
    println(b)
    if(b is Float) {
        println("Float")
    }
    else if(b is Double) {
        println("Double")
    }else if(b is Byte){
        println("byte")
    }else if(b is Int){
        println("int")
    }else if(b is Short){
        println("short")
    }
}

It will provide the output as Int .它将提供 output 作为Int

So i suggest provide data type.所以我建议提供数据类型。

Kotlin Type inference - In Kotlin most of the time, you won't need to specify the type of the objects you are working with, as long as the compiler can infer it. Kotlin 类型推断- 在 Kotlin 大多数情况下,您不需要指定您正在使用的对象的类型,只要编译器可以推断它。

So, we just need to write var or val depending on the type of variable we want to generate, and the type can normally be inferred.所以,我们只需要根据我们要生成的变量的类型,写上var或者val ,就可以正常推断出类型了。 We can always specify a type explicitly as well.我们也总是可以显式地指定一个类型。 Say, for instance, you define val REQUEST_CODE = 100 .例如,假设您定义val REQUEST_CODE = 100 Behind the scenes, REQUEST_CODE initializes with the Int datatype since the value of REQUEST_CODE is of type Int , the compiler infers that REQUEST_CODE is also a Int .在幕后, REQUEST_CODE使用Int数据类型进行初始化,因为REQUEST_CODE的值是Int类型,编译器推断REQUEST_CODE也是Int Note that Kotlin is a statically-typed language.请注意,Kotlin 是一种静态类型语言。 This means that the type is resolved at compile time and never changes.这意味着类型在编译时被解析并且永远不会改变。

Although Kotlin uses Type Inference ( automatically identify something ), which means we also have the option to specify the data type when we initialize the variable like below:虽然 Kotlin 使用类型推断(自动识别某些东西),这意味着我们也可以在初始化变量时指定数据类型,如下所示:

val REQUEST_CODE: Int = 100

Both act the same while converting it to byte code.在将其转换为字节码时,两者的行为相同。

What the heck, How do Kotlin determine the data type of numbers if we use implicit declaration?什么鬼,如果我们使用隐式声明,Kotlin 如何确定数字的数据类型?

Good question, Kotlin provides a set of built-in types that represent numbers.好问题,Kotlin 提供了一组表示数字的内置类型。 For integer numbers, there are four types with different sizes and, hence, value ranges.对于 integer 编号,有四种不同大小的类型,因此有不同的值范围。

在此处输入图像描述

All variables initialized with integer values not exceeding the maximum value of Int have the inferred type Int .所有使用 integer 值初始化但不超过 Int 最大值的变量都具有推断类型Int If the initial value exceeds this value, then the type is Long .如果初始值超过此值,则类型为Long To specify the Long value explicitly, append the suffix L to the value.要明确指定Long值,append 后缀L到该值。 So, whenever you strictly want to save memory it is advisable to use explicit type declaration for data types like Byte & Short as mentioned by Animesh in the accepted answer.因此,每当您严格想要保存 memory 时,建议对像 Animesh 在接受的答案中提到的Byte & Short等数据类型使用显式类型声明。

val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1

Reference参考

Type inference is described in https://kotlinlang.org/docs/reference/basic-types.html https://kotlinlang.org/docs/reference/basic-types.html中描述了类型推断

Basically the default types when not specified for a number in range of -2 31 to 2 31 -1 is Int and higher than that is Long .基本上,当没有为 -2 31到 2 31 -1 范围内的数字指定时,默认类型是Int并且高于Long To specify the Long value explicitly, append the suffix L to the value.要明确指定Long值,append 后缀L到该值。 So, whenever you strictly want to save memory it is advisable to use explicit type declaration for Byte and Short .因此,每当您严格要保存 memory 时,建议对ByteShort使用显式类型声明。

val one = 1                    // inferred as Int
val threeBillion = 3000000000  // inferred as Long
val oneL = 1L                  // explicitly specify Long type by appending with L
val oneLong: Long = 1L         // explicitly specify Long by type
val oneByte: Byte = 1          // explicitly specify Byte for saving memory

For floating point numbers default type is Double , you can switch to float by either specifying type or appending f .对于浮点数,默认类型是Double ,您可以通过指定类型或附加f来切换到浮点数。

val pi = 3.14               // Double
val piFloat: Float = 3.14   // explicitly specify Float by type
val e = 2.7182818284        // Double
val eFloat = 2.7182818284f  // explicitly specify Float by appending with f

The characters and strings by nature having single data type so it is Char and String by default, and there is no need to change it explicitly.字符和字符串本质上是单一数据类型的,所以默认是CharString ,不需要显式更改。

It is generally Advisable to specify types to save memory because it is constant and will never change so conservation is a better choice, but it is all upto you.通常建议指定类型来保存 memory 因为它是恒定的并且永远不会改变所以保存是一个更好的选择,但这完全取决于你。

I'm surprised there are so many answers here ignoring this, but using Byte and Short for properties will not save you memory.我很惊讶这里有这么多答案忽略了这一点,但是使用ByteShort作为属性不会为您节省 memory。 The backing variables still take up 4 bytes of memory for each.后备变量仍然占用每个 memory 的 4 个字节。 They only save you memory when you use them in ByteArray and ShortArray .当您在ByteArrayShortArray They also can cause a performance penalty for doing arithmetic with them instead of Int or Long , but that's insignificant in most applications.它们还可能因使用它们而不是IntLong进行算术运算而导致性能损失,但这在大多数应用程序中是微不足道的。

As other answers have mentioned Int is implicit unless the number is big enough to be a Long .正如其他答案所提到的, Int是隐含的,除非数字大到足以成为Long And this is what you want because it is more performant and takes up the same amount of memory.这就是您想要的,因为它性能更高并且占用相同数量的 memory。

Const is a compilation time constant. Const是编译时间常数。 This means that a value must be allocated during the compilation time, unlike the value that can be performed at run-time, meaning that the const cannot be assigned to a function or class constructor and should only be allocated as character series or basic data type .这意味着必须在编译时分配一个值,这与可以在运行时执行的值不同,这意味着 const 不能分配给 function 或 class 构造函数,并且只能分配为character seriesbasic data type .

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

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