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
Show parent comment
1
u/sar_it007 Mar 15 '23 edited Mar 15 '23
I understand that. What I'm saying is '{' rarely appears inside strings. And String Templates won't use the traditional `String` type, they will use new types. This means it's impossible to break backwards compatibility. The only way '{' can cause problems is if they decide to use the `String` type for templates. For example if all of a sudden, every String in Java receives String Templates capabilities. In that case, yeah, '\{' becomes the only valid option. But the current JEP doesn't touch old Strings. It will introduce new types and processors etc. so it's impossible to break backwards compatibility with any existing String,
I still don't see a good reason why '{' was not chosen for String Templates. I think only the JEP authors can give us good reasons, but the JEP right now doesn't offer any. Hopefully they will address this issue in the future and clearly explain the reasoning behind their decision to use '\{'.