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.
a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
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.
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: Strings are not primitive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With