Update on String Templates (JEP 459)
Guy Steele
guy.steele at oracle.com
Thu Mar 14 15:08:15 UTC 2024
Second thoughts about how to explain a string interpolation literal:
> On Mar 13, 2024, at 2:02 PM, Guy Steele <guy.steele at oracle.com> wrote:
> . . .
>
> —————————
> String is not a subtype of StringTemplate; they are disjoint types.
>
> $”foo” is a (trivial) string template literal
> “foo” is a string literal
> $”Hello, \{x}” is a (nontrivial) string template literal
> “Hello, \{x}” is a shorthand (expanded by the compiler) for `String.of($“Hello, \{x}”)`
> —————————
Given that the intent is that String.of (or whatever we want to call it—possibly the `interpolation` instance method of class `StringTemplate` rather than a static method `String.of`) should just do standard string concatenation, we might be better off just saying that a string interpolation literal is expanded by the compiler into uses of “+”; for example,
“Hello, \{x}.”
(I have added a period to the example to make the point clearer) is expanded into
“Hello, “ + x + “.”
and in general
“c0\{e1}c1\{e2}c2…\{en}cn”
(where each ck is a possibly empty sequence of string characters and each ek is an expression) is expanded into
“c0” + (e1) + “c1” + (e2) + “c2” + … + (en) + “cn”
The point is that, with this definition, “c0\{e1}c1\{e2}c2…\{en}cn” is a constant expression iff every ek is a constant expression. This is handy for interpolating constant variables into a string that is itself intended to be constant.
—Guy
More information about the amber-spec-observers
mailing list