Shohan Ahmed Sijan
Shohan Ahmed Sijan

Reputation: 4531

Kotlin equality showing different output than expectation

Suppose I have a function:

 fun equality() {
        var a = "kotlin"
        var b = "kotlin"
        var c = a
        println(a==b)  //true
        println(a===b) //false
        println(a==c)  //true
        println(a===c) //true
    }

According to kotlin === a and b are different instance, So my expected output is:

true
false
true
true

But actually showing:

true
true
true
true

I can't understand how a===b is true.

Upvotes: 0

Views: 65

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81889

TL;DR: This is specific to strings on the JVM, they are managed in a pool and can be reused to save memory


The JVM internally maintains a string pool which helps to save space for commonly used strings. You can do java.lang.String("kotlin"), i.e. using the standard Java String constructor, to bypass this technique but it's not recommended to not use the Kotlin mapped type kotlin.String.

Let me just crosspost this thread: What is the Java string pool and how is "s" different from new String("s")?

Upvotes: 7

Related Questions