当我将其代码与另一个用户的代码进行比较时,我的代码得出不同的结果。 (Interesting operator '===' in Kotlin)
我正在使用intellij IDEA。
//This is my code
val a: Int = 1
val b: Int? = a
val c: Int? = a
println(b===c) //true
//This is another user's one
val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) //false
我不明白为什么会这样。
答案 0 :(得分:4)
假设您正在JVM上运行代码,则会发生以下情况:
Int?
转换为java.lang.Integer
,Int
转换为原始int
类型。
val boxedA: Int? = a
变为val boxedA: Integer = Integer.valueOf(a)
。 (Integer.valueOf
的框是int
的框)。
Integer.valueOf
的文档:
此方法将始终缓存-128至127(包括)范围内的值,并且可能会缓存该范围之外的其他值。
因此1被缓存,对Integer.valueOf(1)
的多次调用返回相同的Integer
; 10000不会(默认情况下)。
但实际上,===
很少有用。