1

In kotlin nullable values are not preserving identity but equality:

val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'

Why is this different ?

jeanpic
  • 481
  • 3
  • 15
Zumry Mohamed
  • 9,318
  • 5
  • 46
  • 51

4 Answers4

4

This is explained in the documentation right next to this code sample:

Note that boxing of numbers does not necessarily preserve identity

Basically, using the nullable Int? type forces the compiler to use the boxed Integer type for those variables in the generated bytecode instead of the primitive int. So the code sample translates to this Java code:

int a = 10000;
Integer boxedA = Integer.valueOf(a);
Integer anotherBoxedA = Integer.valueOf(a);
System.out.print(boxedA == anotherBoxedA);

This, of course, prints false, since two different Integer instances have been created by the two Integer.valueOf calls. Thought the JVM has caching for the instances created by Integer.valueOf calls, it only works between -128 and 127 - if you run the code with a having a value in that range, both comparisons will indeed return true.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
3

a === b evaluates to true if and only if a and b point to the same object.

That's not true for boxedA === anotherBoxedA.

Kotlin - Equality

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
lkatiforis
  • 5,703
  • 2
  • 16
  • 35
1

Referential equality means that two references point to the same object.

Document, Referential equality is checked by the === operation (and its negated counterpart !==). a === b evaluates to true if and only if a and b point to the same object.

Gowtham Subramaniam
  • 3,358
  • 2
  • 19
  • 31
1

In kotlin , we have two different concepts of equality, Referential equality and Structural equality

Referential equality

We use the === symbol which allows us to evaluate the reference of an object(if it's pointing to the same object). This is an equivalent of "==" operator in java. thats why boxedA === anotherBoxedA return false(Because they are two separate objects, each pointing to a different location in memory).

Structural Equality

We use the == symbol that evaluates if both values are the same (or equal). This is usually achieved by implementing equals() method in java. That's why it boxedA == anotherBoxedA it return true

Suraj Nair
  • 1,729
  • 14
  • 14