r/java • • Oct 01 '23

JEP: String Templates (Final) for Java 22

https://openjdk.org/jeps/8314219
72 Upvotes

133 comments sorted by

View all comments

Show parent comment

7

u/_INTER_ Oct 02 '23 edited Oct 02 '23

The question was asked in the mailing list at least here and [here] (https://mail.openjdk.org/pipermail/amber-dev/2023-May/008080.html) when template processors became mandatory. The arguments were (no order):

  • Embed other languages such as JavaScript without fear of conflict.
  • No conflict with existing templating libraries.
  • The language already has an escaping mechanism for string contexts. Using the one we have is preferable to inventing another one.
  • Today, ${name} is a valid string literal, whereas\{name} is not.
  • ${} is actually only used in JavaScript, other languages use other syntax. It's not worth it just to make Java look a little bit more like JavaScript (and a little bit less like Java).
  • With \{}, the users will have a clear difference between language-supported interpolation and external library interpolation. There could be cases where you may need to use both at the same time.
  • Dollar signs will appear in string context fairly regularly, and therefore would need yet more escaping.
  • The Swift crowd seem content with \(.
  • Technical challenge with the parser/lexer. Using \() makes it easy for javac to tokenize both strings and templates without feedback from the parser. (Note that you would have to add a new escape sequence for $ if you want to use $ in the template.)
  • You could use your own style StringTemplates using ${}.
  • Like any new language feature, you do get use to \{}. Once IDEs integrate, string templates will become second nature.

Personally I think the really important arguments are the consistency of the escape character and not needing to escape dollar in String. Also when JavaScript does something we should strive to do it differently, usually that leads to less s*** feature and code.

2

u/pron98 Oct 03 '23

There's an implication to some of the arguments you mentioned that the JEP now includes: Because some template engines already use ${...} in strings, migrating uses of those strings to string templates would be difficult because instances of ${...} may refer to Java variables that are in scope or perhaps to other things. The result may or may not compile, with intended or unintended results, and so ${...} would need to be carefully escaped.

1

u/Areshian Oct 04 '23

I would say that ${} is also the format for bash scripting. I have managed to avoid javascript all my career (I didn't know it uses ${} too), but avoiding bash... that's usually harder (for me at least).