In Java 15, JEP 378: Text Blocks added three instance methods to String
: stripIndent()
, translateEscapes()
, and formatted(Object... args)
:
The following methods will be added to support text blocks;
String::stripIndent()
: used to strip away incidental white space from the text block contentString::translateEscapes()
: used to translate escape sequencesString::formatted(Object... args)
: simplify value substitution in the text block
The usefulness of formatted
when working with text blocks is explained in the JEP, so its presence makes sense to me.
The other two methods, however, don't seem particularly useful as a developer working with text blocks. Both indentation stripping and escape translation are things that are automatically handled by the compiler with regards to text blocks. A code writer should never need to programmatically strip indentation from a Java text block, nor translate escapes in a text block. Furthermore, escape translation has been in the Java compiler since its initial release, so other than the two new escape sequences added to support text blocks (\s
and \<line-terminator>
), it's not even a new feature to Java.
The JEP explains that the methods are available for developer access, but not the reason for this decision.
The re-indentation algorithm will be normative in The Java Language Specification. Developers will have access to it via
String::stripIndent
, a new instance method.
Developers will have access to escape processing via
String::translateEscapes
, a new instance method.
Why were these methods added to the public String
API alongside text blocks in Java 15, when they're not useful for manipulating text blocks outside of the compiler (or code that otherwise reads Java source code)?
I don't see it explained in the JEP, so I'm wondering if there is any official word or discussion explaining the inclusion of these methods in the public API.
I've done some online searching of the JDK mailing lists, bug trackers, etc. I haven't found a post that fully explains the thought process behind the decision.
I did however find the following comment in the JDK Bug System by Brian Goetz, Java Language Architect at Oracle (emphasis added by me):
It seems the language & API designers want to have the logic used by the language available to developers. This doesn't explain fully explain why they feel it might be useful to users of the API, but it does at least partially explain the decision to include it.