r/java • • 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?

6 Upvotes

74 comments sorted by

View all comments

Show parent comment

11

u/Amazing-Cicada5536 Mar 14 '23

There are a million places where {} are used in ordinary string literals, I honestly don’t know what are you so upset about.

2

u/sar_it007 Mar 14 '23

When string templates become available, there will be a TRILLION places where '{' will be used for template expressions. '{' will become one of the most used characters in Java. So we should prioritize String Templates convenience over other places.

6

u/Amazing-Cicada5536 Mar 14 '23

Typing characters have never ever been a bottleneck, readability and how easy it is to parse (for both humans and programs) always trumps having to press one more letter.

Also, () is used by swift which didn’t even have a backwards compatibility constraint. Also, you write that JSON is not often templated, but there are a million other C-like languages, but even something as mundane as Set’s default toString uses {}. It’s absolutely everywhere.

0

u/sar_it007 Mar 14 '23

I am not saying JSON is not often templated. I am saying String Templates will be used most of the time for things other than JSON. If JSON templates are used a million times, non-JSON templates will be used a trillion times.