Scala String formatting FAQ: How do I write code that is equivalent to the Java String.format class? That is, how do I format strings like that in Scala?
In Java I always write code like this to format a String:
String.format("%s %s, age %d", firstName, lastName, age)
but if you try that in Scala, you'll get a long and unusual error message.
The short answer is that in Scala your String format code will now look like this:
"%s %s, age %d".format(firstName, lastName, age)
As you can see, this appears to be the result of having a format function on a String object. In the old days (before Scala 2.8 or 2.9) this functionality came from the Scala RichString class, but in version 2.9 it comes from the StringLike trait.
I stumbled across this problem and solution today while working on a Scala toString method. I tried to write it like this:
override def toString: String = {
// this won't work in scala
return String.format("%s %s, age %d", firstName, lastName, age)
}
But then learned that the correct approach in Scala is this:
override def toString: String = {
// the correct approach in scala
return "%s %s, age %d".format(firstName, lastName, age)
}
Post new comment