An example of Scala’s `f` string interpolator

With Scala it’s common to embed variables in strings like this with the s string interpolator:

val name = "Fred"
println(s"My name is $name.")

That’s cool, but when you need to format your string, Scala gives you an even more powerful tool: the f string interpolator. Here’s an example of how I just did this in my LittleLogger logging library:

val bw = new BufferedWriter(new FileWriter(new File(LittleLogger.filename), true))
bw.write(f"$time | $logLevel%-5s | $classname | $msg\n")
bw.close

The important line there is the second line, which I’ll repeat here:

bw.write(f"$time | $logLevel%-5s | $classname | $msg\n")

Most of that string looks like I could be using the s interpolator, except for this part:

$logLevel%-5s

What I’m saying there is that I want to print a string that is always five characters wide, and it’s also left-justified. I can specify this formatting because I’m using the f string interpolator instead of the usual s interpolator. The resulting output is shown here, and notice how the second column of information is printed:

04:52:51:541 | INFO  | Bar | this is an info message from class Bar
04:52:51:541 | WARN  | Bar | this is a warn message from class Bar
04:52:51:541 | DEBUG | Bar | this is an error message from class Bar
04:52:51:541 | ERROR | Baz | this is an error message from class Baz

The second column has a constant width, and the text is left-justified. If I didn’t use the minus sign before the 5 in the formatting string, the output would look like this instead:

04:52:51:541 |  INFO | Bar | this is an info message from class Bar
04:52:51:541 |  WARN | Bar | this is a warn message from class Bar
04:52:51:541 | DEBUG | Bar | this is an error message from class Bar
04:52:51:541 | ERROR | Baz | this is an error message from class Baz

and that’s not what I want.

As far as I know, you can use all of the usual printf style formatting strings when you use the f string interpolator. I’ve documented all of those in my popular printf formatting cheat sheet.

In summary, if you wanted a little example of how to use the Scala f string interpolator, I hope this example has been helpful. If you need more information, I have several examples of this in the Scala Cookbook, where I also share examples of Scala’s “raw” interpolator.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.