Why link equality checking returns true when link is different

Consider this code:

fun main(args : Array<String>) {
    println("Async" == MetricCategory.Async.toString())
    println("Async" === MetricCategory.Async.toString())
}

He outputs

true
true

while i was expecting

true
false

Why trueis printed for the second check, since both links are different

+4
source share
2 answers

Referential equality does not mean that the variable name is the same, or it is accessed in the same way as the memory location is the same. Since strings are immutable, the compiler can often reserve memory in advance for them and have all references to the same value point to the same place.

, , . , , . , , , .

+4

, MetricCategory.Async.toString(), . :

class MetricCategory {
    object Async {
        override fun toString(): String {
            return "Async"
        }
    }
}

true, true. , === :

true , a b .

2 ? JVM ( runtimes), string interning:

- , . , , . .

JVM, .

class MetricCategory {
    object Async {
        override fun toString(): String {
            val result = "a".toUpperCase() + "SYNC".toLowerCase()
            return result.intern()
        }
    } 
 }

true, true, , String.intern.

:

println("Async" == "Async") // true, obviously
println("Async" === "Async") // true, string interning for literals
println("Async" == java.lang.String("Async").toString())// true, obviously
println("Async" === java.lang.String("Async").toString()) // false, new instance on the right
println("Async" === java.lang.String("Async").toString().intern()) // true, right changed to shared instance

:

+3

Source: https://habr.com/ru/post/1648712/


All Articles