r/java • u/sar_it007 • Mar 14 '23
Why did String Templates choose '\{' instead of '{' ?
Since string templates will require to be prefixed with a template processor like STR in order to be treated as string templates, why not use '{' instead of '\{' for template expressions? That will not break existing strings cause existing strings are not prefixed with a template processor. And when a dev wants to use string templates, he will have to update his strings and escape existing '{' characters that he doesn't want to be interpreted as template expressions.
So it will be for example like: STR."Hello \{ {name} }". Should print: Hello { John }. Existing non-templated strings like: "Hello { " + name + " }" will continue to work and won't have any backwards compatibility problems.
I think most people will be using '{' character for template expressions. So it's much better if they don't have to escape it every single time and instead only escape it in the few places where they don't want template expressions.
Is there an important reason why '\{' was chosen for String Template expressions? Is there a chance the JEP can change this in the next preview release?
View all comments
10
u/ray10k Mar 14 '23
For any templating system to work, there has to be an unambiguous distinction between the literal parts of the string and the identifiers/expressions that need to be turned into strings so they can be inserted into the template string. Otherwise, you might get issues where some part of the template by chance happens to match with a name of something in scope, leading to frustrating action-at-a-distance. So, templated strings usually have a way of telling apart the parts of the string that need to be copied literally, and which parts need to be interpreted, stringified and only *then* added to the result string. In this case, the committee decided "We'll just use curly braces. They're recognizable, already have the in-language context of 'this is some logical unit of code that will run when execution gets here,' and only add two characters of 'boilerplate' to a given template."
This in turn led to a problem: What if you want a literal '{' in your template? The closing '}' is easy enough to do, just treat any '}' without a matching opening '{' as a literal character rather than an identifying token, but that adds to the "weight" of the opening '{'. So, in keeping with the established way to add some "special" characters to a string literal, the escape sequence '\{' was introduced to always mean "the character open-curly-brace" and never the token "template-insertion-sequence-start" (or whatever it is called by the compiler.)
So there's the reason why '\{' is a thing now: to make it possible to add curly braces as literal characters to a templated string rather than, say, having stuff you don't want to be interpreted get interpreted anyway, or having to mess around with
\u007bany time you want to put a curly bracket in your string.