The Dollar Sign ($) in Scala


#1

In Perl and Bash Shell-like environments the dollar sign is used to declare a variable.

I found some nice code snippet here in Forum, which helped me with some of my understandings considering Scala (very much appreciated! :slight_smile: )

targets.foreach(t => println(s"$t: ${getCapitals(t)}"))

can someone please take apart this line, and explain how it works? I have taken it, that " $t " is just short for " $targets ", which we named apriori. Found out that when I do write it, it will just give " List ", and seems to jump out the foreach-loop.

Here is the whole code:

val countryCapitals = Map(
“Germany” -> “Berlin”,
“Russia” -> “Moscow”,
“Finland” -> “Helsinki”)

def getCapitals(country: String): String =
countryCapitals.get(country) match {

case Some(capital) => capital
case None => “unknown”
}

val targets = List(“Germany”, “Russia”, “New York”)

println( " Read capitals:" )
targets.foreach(t => println(s"$t: ${getCapitals(t)}"))


#2

This is string interpolation. Read here:
https://docs.scala-lang.org/overviews/core/string-interpolation.html


#3

In Scala, variables are not marked with dollar signs, except in String interpolation.

s"$t: ${getCapitals(t)}"

is just a more convenient way to give you the same result as:

t.toString + ": " + getCapitals(t).toString

So, $t refers to t, not targets, where t is the argument of this function:

t => println(s"$t: ${getCapitals(t)}")

The foreach method takes a function and applies it every element in the List.


#4

One things that should be mentioned about the original post. HashBang said that "$t is just short of $targets". That isn’t correct. The t in $t comes from the t => at the beginning of the foreach. This is a lambda that binds each value in targets to the name t in turn. As others have pointed out, the dollar sign is just used by string interpolation to say that the next word should be treated as a variable name.


#5

thanks a lot!
Always fascinating to learn new stuff, after so much time of programming practice


#6

will read into that