O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

String Interpolation

Creating a string form of output or messages is a chore in Java. For example, it takes effort to create a message “A discount of 10% has been applied” where the value 10 comes from a variable named discount. You may write:

String message = "A discount of " + discount + "% has been applied"

In addition to the effort, the code is hard to read. Alternately, you could write:

String message = String.format("A discount of %d% has been applied", discount);

But that’s verbose too. Scala provides a fluent and concise syntax to create string literals with expressions. Here’s the Scala equivalent that produces the desired message:

 
val​ message = s​"A discount of $discount% has been applied"

That leading s before the double quote ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required