Unexpected result when comparing CharSequence.reversed() return value


#1

Have noticed a strange behavior when comparing a result of CharSequence.reversed() method.

val s = "a"
val subSequence = s.subSequence(0, 1)
println("$subSequence == ${subSequence.reversed()}: ${subSequence == subSequence.reversed()}")

Results in:

a == a: false

Moreover subSequence.reversed() == subSequence.reversed() is also false.

Can someone explain why this happens?


#2

I dont know.
I know that the returnvalue of subSequence is CharSequence.
CharSequence has no defined implementation of equals, just like Java’s Charsequence.
Therefor the return-value doesn’t have to be true.


#3

This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. It is therefore inappropriate to use arbitrary CharSequence instances as elements in a set or as keys in a map.


#4

Note that this is the Java documentation. Kotlin’s documentation, as usual, is pretty much absent apart from obvious things.