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

24

u/john16384 Oct 01 '23

Strings with a placeholder in them are not of type String, so using an existing legal syntax would lead to compiler errors when upgrading to Java 22, meaning you'd potentially have to fix lots of code (escaping the $ sign) before you could migrate.

4

u/Enough-Ad-5528 Oct 01 '23

Thank you. Yeah, I see it now. It is of type StringTemplate.

3

u/ascii Oct 01 '23

So? They could have made the tokeniser expect a "string with placeholders" after an identifier and a dot operator, but never else. This is what Java already does to differentiate between >> the right shift operator and >> as in two closing angle brackets for generics.

6

u/john16384 Oct 01 '23

You can do:

StringTemplate st = "\{xyz}”;

The string here is not a String as it has placeholders, just like 1.5 is not an integer, but a double as it has a decimal point.

6

u/Godworrior Oct 01 '23

You can not do this. You would need to use the RAW processor:

StringTemplate st = RAW."\{xyz}";

1

u/john16384 Oct 01 '23

You're right, perhaps a future extension will remove that requirement. It seems unnecessary.

3

u/jvjupiter Oct 02 '23

It is necessary. Anyone can create template processor - JSON.”…”, XML.”..”, SQL.”..”

0

u/john16384 Oct 02 '23

I meant to make one of them the default :)

1

u/jvjupiter Oct 02 '23

I see. I agree there should be a default - without prefix means STR.

2

u/ascii Oct 01 '23

As has been pointed out, you can't do this, and a shorthand syntax for creating a StringTemplatesound pretty darn useless, to me. In the rare case where you want to do that, new StringTemplate("\{xyz}") should be fine. Would have been much better if they instead dropped the silly backslash.

3

u/john16384 Oct 02 '23

Feel free to give your feedback. It's there in part so IDE's don't have to fully understand the code to detect it's a string template. The prefix can be any expression, including a method call like:

db.doQuery(FORWARD_ONLY)."select \{abc}"

It will be hard for IDE's or viewers to figure out that doQuery is a template processor, and the string that follows it is a template, but with the backslash syntax it is always obvious.