Reputation: 291
var a: Int = 10000
var b: Int = 10000
print(b === a) // Prints 'true'
The official doc says: "a === b evaluates to true if and only if a and b point to the same object."
In the codes above, what's "the same object"?
Upvotes: 1
Views: 865
Reputation: 9388
===
means we have to check the referential equality between the objects.
var a: Int = 10000
var b: Int = 10000
print(b === a)
It prints true because the reference to a
and b
variables are same. It's actually not an object. As the value of a
and b
are same that's why their reference is also same. a
and b
refers to the same memory allocation as their value is same. a
and b
are primitive type variables. So, you will get a warning
Identity equality for arguments of types Int and Int is deprecated.
var c = Integer(10000)
var d = Integer(10000)
print(d === c)
It prints false because c
and d
are two different Integer objects. So, the reference to c
and d
are also different.
Upvotes: 2
Reputation: 7001
If you imagine inside the JVM there are 2 types that are stored directly:
Primitive types [Int
, Long
]
These are stored as the value
Reference types [String
, Object
]
These are stored as a reference to the object
===
work===
compares the values in memory, so for reference types it checks they refer to the same object, whereas for primitive types it checks that they hold the same value.
Int
s primitive objectsKotlin stores types that can be stored as primitives as primitives as an optimisation, so Int
is primitive, whereas Int?
would be stored as a reference type.
Upvotes: 1