Shawn Plus
Shawn Plus

Reputation: 477

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

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

Answers (3)

s1m0nw1
s1m0nw1

Reputation: 82087

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.

Upvotes: 4

guenhter
guenhter

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 like a == 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

Related Questions