0

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.

Shohan Ahmed Sijan
  • 4,391
  • 1
  • 33
  • 39

1 Answers1

7

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")?

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196