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 ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.