scalastring-interpolationscala-repl

scala string interpolation for "$"


Why does string interpolation not work when the name of value of '$'?

In the following code, why does the value of $ not get printed? What is the mistake when the value of x is printed using string interpolation?

repl> val x="test value"
repl> val $="some value"
repl> println($)
some value
repl> println(s"value:$x")
value:test value
repl> println(s"value:$$")
value:$

Why is the $ not replaced by its value?


Solution

  • To actually print the value of the variable represented by $, you should enclose it in braces:

    println(s"value:${$}")
    

    outputs:

    value:some value
    

    Doubling the $ sign does not work because it is used to escape $ itself as explained here.