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.

October 13, 2008

NumberFormatException

scala> "true".toBoolean
res1: Boolean = true


That's pretty cool. Does it work for "false" too?

scala> "false".toBoolean
res1: Boolean = false


Yeah! Awesome! How does it handle other values, I wonder?

scala> "1".toBoolean
java.lang.NumberFormatException: For input string: "1"


... Err, what?