concept identity in category kotlin

appears as: identity, identity
The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

Equality versus identity

One of the classical pitfalls in Java is the possible confusion between equality and identity. This problem is made even trickier due to the presence of primitives, the fact that strings are interned, and the way in which Integers are handled:

// Java code
int a = 2;
System.out.println(a == 2); // true
Integer b = Integer.valueOf(1);
System.out.println(b == Integer.valueOf(1)); // true
System.out.println(b == new Integer(1)); // false
System.out.println(b.equals(new Integer(1))); // true
Integer c = Integer.valueOf(512);
System.out.println(c == Integer.valueOf(512)); // false
System.out.println(c.equals(Integer.valueOf(512))); // true
String s = "Hello";
System.out.println(s == "Hello"); // true
String s2 = "Hello, World!".substring(0, 5);
System.out.println(s2 == "Hello"); // false
System.out.println(s2.equals("Hello")); // true

What a mess! (In case you wonder why the integers b and c behave differently, it’s because Java returns a memoized shared version of integers for low values, so Integer.valueOf(1) always returns the same object, whereas Integer.valueOf(512) returns a new distinct object on each call.) To be safe in Java, always test equality with equals for objects and with == for primitives. The == symbol tests equality for primitives and identity for objects.

Kotlin is simpler. Identity (also called referential equality) is tested with ===. Equality (sometimes called structural equality) is tested with ==, which is a shorthand for equals. The simple fact that testing for equality (==) is simpler than testing for identity (===) will prevent many mistakes. You can negate both == and === by replacing the first = with a !.