2

According to the docs, === performs referential equality.

Given the following referential equality comparisons, this doesn't seem to work in all cases:

val x = "A"
val y = "A"

println(x === y) // "true"
println("A" === "A") // "true"

I would expect both of those cases to return false.

Yet this example returns false as expected:

val x = readLine()!! // "A"
val y = readLine()!! // "A"

println(x === y) // "false"

So why does referential equality comparison work for the latter case, but not the former?

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313

1 Answers1

3

The === basically means "are these objects of the same type and do they point to the same memory address?"

In your first example, both x and y point to a constant A, which, as a String constant, there is a single instance of, so they return true.

When you read from a file, an allocation takes place for the string read, and thus, x and y point to different memory addresses, so they are equal (== returns true), but not identical (=== return false).

Francesc
  • 25,014
  • 10
  • 66
  • 84