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?
s is a method Scala provides other off-the-shelf interpolation functions to give you more power. You can define your own string interpolation functions.
Bookmark this question. Show activity on this post. Scala has triple quoted strings """String\nString""" to use special characters in the string without escaping. Scala 2.10 also added raw"String\nString" for the same purpose.
Beginning with C# 10, you can use string interpolation to initialize a constant string. All expressions used for placeholders must be constant strings. In other words, every interpolation expression must be a string, and it must be a compile time constant.
String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With