scala string interpolation for "$"

279 Views Asked by At

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?

1

There are 1 best solutions below

0
jrook On BEST ANSWER

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.