Search code examples
stringscalastring-interpolation

Can you print $ in Scala string interpolation?


In Scala, I want to print the price of some item with string interpolation. Is it possible to display the $ character with interpolation? This works:

scala> println(s"It only costs ${3 + 4} dollars")
It only costs 7 dollars

So why does this not work? It should still say $7, according to the docs

scala> println(s"It only costs $${3 + 4}")
It only costs ${3 + 4}

Solution

  • You need a third $ to the actual interpolation too. The following should work:

     s"It only costs $$${3 + 4} dollars"
    

    The first two $s are for the $ sign in the output, the third is for the interpolation. It might be easier to see this way:

     s"It only costs $$ ${3 + 4} dollars"