Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why kotlin use === compare primitive type equal each other if they has same value

Tags:

kotlin

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.

like image 883
Shawn Plus Avatar asked Dec 21 '25 14:12

Shawn Plus


2 Answers

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.

like image 181
Alexey Romanov Avatar answered Dec 24 '25 08:12

Alexey Romanov


Equality in Kotlin

I explained the general equality tools used in Kotlin in this answer. TLDR:

  1. structural equality: == is compiled to Java's equals

  2. Referential equality: === is what == does in Java: References are compared to each other. It yields true if the same objects are being compared.

What about Strings like in your example?

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.

like image 24
s1m0nw1 Avatar answered Dec 24 '25 10:12

s1m0nw1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!