Reputation: 477
val hello1 = "hello"
val hello2 = "hello"
printf(hello1 === hello2)
why print true?
I guess kotlin has a primitive type pool(or something like that). If the value is equality,a pointer points to same place.I'm not sure.
Upvotes: 2
Views: 4252
Reputation: 82087
I explained the general equality tools used in Kotlin in this answer. TLDR:
structural equality: ==
is compiled to Java's equals
Referential equality: ===
is what ==
does in Java: References are compared to each other. It yields true
if the same objects are being compared.
Strings are special in that they work with a so called string constant pool. For example, even in Java, the following is true
for both comparisons:
public static void main(String[] args) {
String s = "prasad";
String s2 = "prasad";
System.out.println(s.equals(s2));
System.out.println(s == s2);
}
On the other hand, the next snippet does work differently since new
Strings are being created:
String foo = new String("hello");
String bar = new String("hello");
System.out.println(foo == bar); // prints 'false'
Read about it here: What is the Java string pool and how is "s" different from new String("s")?
FYI: String
s are not primitive.
Upvotes: 4
Reputation: 12177
https://kotlinlang.org/docs/reference/equality.html
In Kotlin there are two types of equality:
- Referential equality (two references point to the same object);
- Structural equality (a check for equals()).
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.Structural equality is checked by the
==
operation (and its negated counterpart!=
). By convention, an expression likea == b
is translated to:So you see
a?.equals(b) ?: (b === null)
So you see: ==
means equals
and ===
means referential equality
That would imply that
val hello1 = "hello"
val hello2 = "hello"
printf(hello1 === hello2)
is referential compared which should lead to false
.
BUT: When you use a string literal like "hello"
, the string cache of java is used (this is an optimization to save memory). So you get both times the same reference, and therefore the reference equality is true.
Upvotes: 2
Reputation: 170899
Kotlin simply reuses the same mechanism. See Is String Literal Pool a collection of references to the String Object, Or a collection of Objects and Java String literal pool and string object for additional explanations.
Upvotes: 7