October 24, 2008

Scala RichString is not comparable to String

A sadness:
val r: scala.runtime.RichString = "1"
val s: String = "1"
if (r == s) {
println("ok1")
} else {
println("sad1")
}

if (s == r) {
println("ok2")
} else {
println("sad2")
}

if (s.equals(r)) {
println("ok3")
} else {
println("sad3")
}

if (r.equals(s)) {
println("ok4")
} else {
println("sad4")
}

Will print:
sad1
sad2
sad3
sad4

This isn't as sad as:
sad1
ok2
sad3
ok4
which would precipitate Robey's "ultimate sadness".

I got into this state by adding a .drop to a String, and chaos resulted. The details are tangentally described in: http://www.nabble.com/String-and-RichString-equality-td14888607.html

Still, this is another thing to keep in your head when coding along. I suppose it's best to coerce RichStrings back to Strings immediately, so as not to allow RichStrings to propagate too far.

1 comment:

martin said...

This is a known problem. We'll fix it (one way or another) in 2.8.0.