The Scala String format approach (and Java String.format)

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?

NOTE: As of Scala 2.10 this approach is out of date. The preferred approach is to use the Scala String interpolator method.

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 Scala String formatting approach

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 through 2.12 it comes from the StringLike trait. In more modern Scala versions you may want to see the StringOps class. (Again, this is an old web page, and I’m just trying to update those links to help your research.)

My Scala toString method

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)
}