Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
dexter2305 Avatar asked Oct 09 '19 20:10

dexter2305


People also ask

Why is s used in Scala?

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.

What is triple quotes in Scala?

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.

Can I use string interpolation?

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.

Which strings do interpolate variables?

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.


1 Answers

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.

like image 166
jrook Avatar answered Sep 20 '22 08:09

jrook