A very useful feature of many programming languages is string interpolation. It is a great syntax for concise string formatting. An interpolated string is nothing more than a template to be used to output formatted text. And that is the primary responsibility of the interpolation feature. Scala supports two modes of interpolation: value and expression.

val name = "Ozzy"
val surname = "Osbourne"
// value interpolation
val fullname = s"$name $surname"
  
// expression interpolation
val lengthMessage = s"Number of letters in the name ${name.length}"

And this is where I like Scala’s syntax a lot - to eliminate parsing ambiguity, expressions need to be enclosed by braces, which makes an interpolated string look very ugly. And when something is ugly in the code, it makes me think about what’s wrong with it. Well, there’s a problem - all expressions have their own responsibilities already. In the example above, the expression is used to calculate the name’s length, which is a separate responsibility on its own and placing the length calculation into the template is a violation of Single Responsibility Principle.

While I don’t want anyone to blindly follow this rule of not using expression interpolation in their code, in general I believe it’s a good habit to prefer value interpolation over expression interpolation. It will make the code more readable without those distracting curly braces sprinkled through strings. And it leads to a clearer separation between responsibilities in the code. If you let expressions creep into the code, they may end up as hard-to-find side effects (calling external APIs, invoking an expensive cache refresh).

Scala allows you to put values into braces too, but why would you do that? Don’t upset people who read your code.