In Scala 2.10 a new string interpolator feature has been added (see here).
val name = "James" println(s"Hello, $name") // Hello, James
What is not clear to me is whether this feature is an ad-hoc addition or whether it is syntactic sugar for some other, more general construct.
The only thing I can think of is that the compiler turns a string literal like
into an expression like
"Hello, " + name
but still, this seems to me a very special treatment of string literals (see also the related question on XML literals). Or is this a particular application of some more general Scala construct?
Thanks for the feedback. I had read the whole article but probably my summary was not accurate enough, making the point of my question unclear. Thanks to Jörg for the good summary.
What puzzles me is that the compiler expands a special string literal into an expression that contains names defined inside the string itself. The resulting expression must be re-compiled to check that the names of the arguments used to call the
StringContext instance are defined in the current lexical scope.
This looks like some kind of pre-processing to me (first pass: expand special literals, second pass: compile) because the value of the token
s"Hello, $name" is preprocessed and expanded into a whole sub-tree of the syntax tree.
This expansion is built-in into the compiler: as far as I know it cannot be defined in terms of the language itself by means of more primitive features taking the string literal as it is as input because the names defined inside the string must be extracted and interpreted as variables from the lexical scope.
For example, (as far as I understand) no Scala method can be called with the string "Hello, $name" and find out that there is a variable
name in the lexical scope of the expression where the method has been called.
Therefore, it is the compiler that has to write out
and then re-compile the result, check that the variable
name exists, and generate a proper method call.
Summarizing, I find this reference to a variable in the lexical scope from within a string literal very strange, it seems something is happening on a different level of the language. I do not know how to explain this in a better way.