Kotlin盒装Int不一样 [英] Kotlin boxed Int are not the same
问题描述
请帮助我理解kotlin文档中的这段代码:-
Please help me understand this piece of code in the kotlin docs:-
val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
现在,我了解到首先是int a = 10000
,然后在下一行中它是使用===
进行比较.
Now, I understand that first int a = 10000
then in the next line it is comparing it using ===
.
现在的问题是,为什么分配boxedA=a
时使用int?
检查它是否为空.可以这样写吗:-
Now the question is why when it assigned boxedA=a
, it checked if it is null using int?
. Can it just be written like this:-
val boxedA: Int=a
如果我理解错误的方式,请有人指导检查正确的地方或为我解释一下.
Please if I'm understanding it the wrong way, someone guide to check the right place or explain it a bit for me.
推荐答案
在分配
boxedA = a
时,它使用int?
我不知道你是什么意思.使变量的类型为Int?
使其成为可以存储Int
或null
的变量.这项作业没有检查.如果您要为该变量分配一个非null值,只需将其设为非null即可,而无需输入?
类型:
I have no idea what you mean by this. Making a variable have the type Int?
makes it a variable that can either store an Int
or null
. There is no checking happening at this assignment. If you have a non-null value to assign to the variable, just make it non-nullable, without the ?
in the type:
val copyOfA: Int = a
您甚至可以省略类型,并推断出Int
:
You can even omit the type, and get Int
inferred:
val copyOfA = a
至于比较:
As for the comparisons:
==
用于按Kotlin中的值进行比较(这相当于在Java中使用equals
),===
用于比较引用(在Java中为==
).
==
is used for comparing by value in Kotlin (this is the equivalent of using equals
in Java), ===
is used for comparing references (this is ==
in Java).
创建boxedA
和anotherBoxedA
时,将在后台创建两个Integer
实例(因为可空变量不能用基元表示).与==
(它们具有相同的值)相比,它们是相等的,但与===
(它们是不同的实例)相比,则不相等.
When you create boxedA
and anotherBoxedA
, you create two Integer
instances under the hood (because nullable variables can't be represented by primitives). These will be equal when compared with ==
(they have the same value), but not when compared with ===
(they are different instances).
您可以在此处看到官方文档的相关部分.
You can see the relevant part of the offical docs here.
这篇关于Kotlin盒装Int不一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!