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 it comes from the StringLike trait.

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

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.