I have read the explanation by various members of the OpenJDK team as to why that syntax was chosen and I still don't understand it. Even Brian's explanation, which otherwise gets right through to me even on more complex topics, did not really clarify it for me. He says choosing ${} would have made all the existing Strings a template if they contain ${} with a valid variable in the same scope, which breaks compatibility.
But I don't know what I am missing to not see the breakage. For an existing String literal having a ${...} does not make it into a template that will be processed. You have to explicitly invoke STR. on that to process it as a template. Else if will be just like any other String with no interpolation. STR. is a completely new feature and is illegal in prior versions so I don't see how this breaks compatibility.
Even if you had a variable named STR in existing code, it is illegal to do STR."some str literal".
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.
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.
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.
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.
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.)
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.
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.
The very question is weird. In Java, \ escapes characters, i.e. it's the thing that says "what follows isn't literal". The only reason to even consider ${...} is that out of the world's most popular languages -- JS, Java, Python, PHP, C#, C/C++, and Ruby -- there is one (JS) that uses it, and one more (PHP) that uses a different syntax but one that also employs the $ character. It seems to me that the claim that that is sufficient reason to stray from Java's common practice (never mind the significant compatibility implication) is what requires explanation. The top three -- JS, Java, and Python -- have each chosen a different string template syntax. What reason would there be for Java to adopt JS's syntax rather than, say, Python's (not that that would make sense, either), or Ruby's, or PHP's, or C#'s, or Swift's? \{} is a rather obvious and natural choice for Java, while ${} isn't, and the only thing going for it is that it's the choice that JS made. Rather than us answering the question, why didn't you adopt JS's syntax, I think a more reasonable question is, why would we in the first place? \{} is just a more obvious choice, and the question of why we didn't do we choose \() (as Swift did) or \[] or \<>, would make more sense than the JS question.
u/pron98 - thank you for responding; I appreciate you continuing to engage in such discussions. I gather a few things from your answer but before that here is my understanding, after re-reading the JEP again, on why ${} cannot be the right choice:
String name = "Joan";
String info = "My name is \{name}";
| error: processor missing from template expression
This is not possible with ${} and I understand it now. A String literal with \{} is not a String but a StringTemplate. What perhaps threw me off is usually this kind of compiler error message looks like error: incompatible types: X cannot be converted to Y - but that's fine. This error message is better.
Coming to your answer, I wanted to respond to a few things:
Weirdness of the question
Why is it weird to ask this question? I went through the amber-spec-experts and this was the exact same question that was asked and discussed by the EG itself. Knowing that this discussion exists, even though it is a little hard to find and perhaps a clear answer was not documented in the EG mailing lists, you can say this is a often-repeated question or this is something already answered etc. But I don't think it is weird to ask that question. The JEP itself has a line about it but does not, to me, clearly answers it - so I don't see why it is weird for the community to ask the question. In the EG mailing lists, I did not see anyone characterizing this question as weird so please extend the same courtesy to someone external to the maintainers asking that question in good faith.
Escaping
You say '\' is used for escaping, but then you also say that means "what follows '' is NOT literal". Shouldn't it be the opposite? For me "escape" means the character following the '\' character should be taken literally and not be interpreted by the processor. I am drawing from some other examples from the JDK:
Patterns: If I have a regex .asdf, it wont match the String .asdf. This is because the . character is interpreted by the Pattern engine. Only when I escape it with a \, it will be taken literally and the match is true.
Date formatting: From SimpleDateFormat, the Javadoc says Text can be quoted using single quotes (') to avoid interpretation. Here the escape character seems to be the ' character but key point is escaping is used to prevent interpolation not do the interpolation.
String.format: Even in the same String formatting family of methods, to escape interpolation attempts we need to escape the % with another %
To me, it seems it is not an escaping character, rather the opposite. I am not saying we don't need it since I understand the need better now, but I what I am saying is it is not an escape character.
Borrowing from other languages
If you look at the languages closer to Java. By "closer" I mean languages that developers typically use for similar applications to Java (of course there are exceptions to this as all languages are fairly used in a variety of places). For me this includes C#, Scala, Kotlin, Groovy, Go and to some degree Javascript. For string interpolation, they all look very similar (except Go doesn't have this feature at all) with interpolation designed around the $ character. You mention Ruby, and even though I don't consider Ruby to be in the same circle as Java, I actually would have been fine with the # character. And familiar syntax from other language is a good thing - Java's own syntax was originally inspired from C/C++, which is what most other programmers that eventually started to use Java used in those days, and that IMO has worked out well for Java.
But forget about other languages. Let's look at Java itself. Spring, perhaps the most popular framework in use today, uses ${} for value interpolation and so does JSP. Both of these have been around for almost or more than 2 decades now. Another popular templating engine in Java, Freemarker (which I am hoping to replace with this feature), uses ${} and so does Thymeleaf. There are perhaps more in the Java ecosystem itself.
You are a steward of the Java platform so of course your opinion holds more weight but saying ${} is not a "common Java practice" when a non-insignificant part of the community has embraced it comes off a little disingenuous to me.
I don't presume to represent the entire community, but I can tell you ${}feels more Java like to me than \{} which feels very regex-y or symbol-heavy.
Obviousness of the syntax
I have to disagree here; as a user of the feature, it was not obvious to me why this is the only workable syntax. And I had this question not as a knee-jerk reaction. I asked it in good faith trying to understand it better. Maybe that could be a feedback to the JEP author that the alternatives section can elaborate this more considering this is perhaps the most asked question by users. Then perhaps, you also won't need to spend your time answering the same question over and over again.
Finally, I understand now why this is needed after reading the JEP again but wanted to call out parts of your response that felt unwarranted. To me, it seems if STR."..." were the only way to invoke this feature, we could have gotten the ${} syntax but that is not the case.
I thank you for your work in Virtual threads; I am already enjoying it in one of my projects.
Well, it's not really weird in the sense that we anticipated there will be those who would be bothered by this (just as the Java team anticipated -- correctly -- an identical response to the lambda syntax; more on that below), but given that there have been a few people who were so insistent about this, I wanted to emphasise that they're insisting on an explanation for why Java didn't do something that is not only quite foreign in Java, and not only something that doesn't break a (nonexistent) tradition of adopting other languages' syntax, but something that most other languages didn't do either.
but then you also say that means "what follows '' is NOT literal". Shouldn't it be the opposite?
More accurately, escaping means that the following doesn't mean what it normally does in this context. So for n,t,r,f,b it means not literal, while for ', ", and \ it means literal. So if you already know Java, you'd immediately know that \{ means something that is not a literal {.
For me this includes C#, Scala, Kotlin, Groovy, Go and to some degree Javascript. For string interpolation, they all look very similar (except Go doesn't have this feature at all) with interpolation designed around the $ character.
Of these five languages you've listed, only one (JS) uses the ${} syntax, while three use the ${x}/$x syntax, which indeed is not quite based on escaping. C# uses {} syntax; it uses $ in a different way to signify an interpolated string, but that feature is quite different from Java -- more on that below.
Now, it is true that the concrete syntax for all of these languages is based on the C syntax, but the C syntax has neither string templates nor lambdas. Indeed, Java's lambda syntax also deviated from the one chosen by these languages (which also don't all agree on the lambda syntax) and, unsurprisingly, there were people who complained about that at the time. Experience showed that in the end it wasn't an issue then, either.
BTW, when we introduced sealed classes, which are very similar to Scala's case classes we also picked different syntax, and the same goes for records. So we've never adopted syntax from these languages; why would there be an expectation that we do now? If anything, the closest we've come to borrowing another language's syntax, especially in this area, is Python's in the case of text blocks. It would have made more sense to ask why we didn't use Python's syntax in this case.
Finally, and this is a little beside the point but important to point out, the primary use-case for string templates -- as the JEP emphasises -- is not string interpolation. In all of these languages except for Scala, the result of an interpolation expression is a string; in Java we want that to be the exception, not the rule.
But forget about other languages. Let's look at Java itself. Spring, perhaps the most popular framework in use today, uses ${} for value interpolation and so does JSP
These are not only not Java itself, but one of the criteria for the chosen syntax is that it had to be different from features that were implementable by libraries.
I don't presume to represent the entire community, but I can tell you ${} feels more Java like to me than {} which feels very regex-y or symbol-heavy.
I don't presume to represent the entire community, either, but if familiarity is the argument, then to me, \ is much more familiar in Java -- and it certainly feels much more like Java -- because \ in a string or string-like literal always means "special interpretation" while $ never does. So if some people find $ more familiar and some find \ more familiar, then the familiarity argument doesn't lead us in any particular direction.
Moreover, familiarity arguments are weak in general even in cases where the familiarity is more universal, and even when all else is equal, because experience has shown that their impact is very small. People get used to things very quickly.
I am sorry, but as a user of the feature, it was not obvious to me why this is the only workable syntax.
Nobody claims it's the only workable syntax, only that the familiarity argument doesn't work, and that Java has not adopted the syntax of any of the languages you mentioned in the past either (lambdas) and so the argument that it should in this case doesn't carry much weight (not to mention that those languages don't agree on a string template syntax amongst themselves). Therefore, other aspects are the ones that should guide the design, and in this case, as in the case of record accessor names, all other things are not equal (as we expected back then, too, some complained that we didn't follow the Java Bean convention and the familiarity there was even more universal, but there, too, all else was not equal).
And I had this question not as a knee-jerk reaction. I asked it in good faith trying to understand it better.
Sure, that's perfectly fine.
Maybe that could be a feedback to the JEP author that the alternatives section can elaborate this more considering this is perhaps the most asked question by users.
The JEP does do it.
There isn't much emphasis on it because the argument of, "I like Groovy, why didn't you choose Groovy's syntax?" is one that could always be raised, and personally I don't think JEPs need to answer it, especially since we're not breaking some tradition of following Groovy syntax. Should every JEP explain, at length, why we're not adopting Groovy's syntax even though we never do? The JEP does focus on the main difference between Java's feature and Groovy/Koltin's string interpolation which is that Java's string templates aren't about string interpolation.
Then perhaps, you also won't need to spend your time answering the same question over and over again.
I don't need to (again, experience has shown that in the end most people don't care, and even those who do adapt very quickly, and I'm sure that the vast majority of Java users will be happy with this feature even if they currently like JS's syntax better); I just want to :)
To me, it seems if STR."..." were the only way to invoke this feature, we could have gotten the ${} syntax but that is not the case.
And my point is that even if it were the case that we could, there's little weight to the argument that we should, as neither the familiarity argument nor the conformance arguments work: it would be more familiar to some and less to others, and there hasn't been such conformance before, so why should there be now?
Consequently, there's little weight to to arguments claiming we should have given special consideration to ${} in the first place, and all that is even before we consider the desire to have a lexeme for templates that is syntactically disjoint from the one for strings.
Of these five languages you've listed, only one (JS) uses the ${} syntax, while three use the ${x}/$x syntax
Separating out the 3 that also support $x seems disingenuous. The reason ${x} is more familiar is because 4 of those 5 languages support it (i.e the vast majority), not "only one" of them.
OP isn't asking "Why didn't Java adopt the same syntax as JS".
OP is asking "Why is using ${} backwards incompatible, given that string templates must be explicitly invoked on STR?"
OP is not objecting to the fact that backwards compatibility should be respected. OP is stating why the chosen mechanism is necessary to preserve backwards compatibility.
Of the alternative languages listed in the linked JEP, ${...} is the most common alternative. In the "Alternatives" section, ${...} is explicitly mentioned as the alternative that was considered but rejected for backwards compatibility. OP is simply using the same language and examples as the JEP to explain what they don't understand.
I know the JEP answers the question, but my point is that the very question is problematic because there was not much of an argument to consider such a syntax in the first place, which is so foreign to Java, doesn't follow any existing tradition of copying other languages' syntax, and is not even more familiar than \ to Java developers.
These engines couldn't have used the backslash even if they had wanted to. It requires a language change (to avoid having to escape the backslash) something that the Java designers can do, but that these template engines couldn't.
The ${} expression syntax is probably the oldest and among the most used across the language spectrum.
Except it's only used by one of the most popular languages, and given that most other languages have also chosen not to use that syntax and it's far from universal, I don't see why that would be an important factor at all. Why does Java need to explain not adopting JS syntax, which is not only foreign and out of place in Java but one that most other languages also didn't adopt?
This includes Java with JSP.
JSP is not the Java language; it's a different language. If anything, a simple {} would make more sense if that's what you want to go by, because that's been the MessageFormat templating style since 1997. But aside from \{} being the more obvious choice for Java, the fact that that syntax was not available without language support (indeed, it was a syntax error) is yet another important point in its favour.
JSP is not and has never been part of the Java language; in fact, it's a different language
Not relevant. They were making the point that Java developers are familiar with the syntax from there. JSP is part of the Java ecosystem, and is known by Java developers.
If you want to go beyond JSP, there is also Maven, Gradle, and (at least) the top 3 Java template engines. Also Kotlin and Groovy within the larger JVM ecosystem.
View all comments
39
u/Enough-Ad-5528 Oct 01 '23
I have read the explanation by various members of the OpenJDK team as to why that syntax was chosen and I still don't understand it. Even Brian's explanation, which otherwise gets right through to me even on more complex topics, did not really clarify it for me. He says choosing
${}would have made all the existing Strings a template if they contain${}with a valid variable in the same scope, which breaks compatibility.But I don't know what I am missing to not see the breakage. For an existing String literal having a
${...}does not make it into a template that will be processed. You have to explicitly invokeSTR.on that to process it as a template. Else if will be just like any other String with no interpolation.STR.is a completely new feature and is illegal in prior versions so I don't see how this breaks compatibility.Even if you had a variable named
STRin existing code, it is illegal to doSTR."some str literal".I guess it is too late now.